Skip to content

Commit 27100d9

Browse files
added smith number program
1 parent e21aee8 commit 27100d9

File tree

2 files changed

+74
-0
lines changed

2 files changed

+74
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
package com.thealgorithms.maths;
2+
3+
import com.thealgorithms.maths.Prime.PrimeCheck;
4+
5+
/**
6+
* In number theory, a smith number is a composite number for which, in a given number base,
7+
* the sum of its digits is equal to the sum of the digits in its prime factorization in the same base.
8+
*
9+
* For example, in base 10, 378 = 21 X 33 X 71 is a Smith number since 3 + 7 + 8 = 2 X 1 + 3 X 3 + 7 X 1,
10+
* and 22 = 21 X 111 is a Smith number, because 2 + 2 = 2 X 1 + (1 + 1) X 1.
11+
*
12+
* Wiki: https://en.wikipedia.org/wiki/Smith_number
13+
*/
14+
public class SmithNumber {
15+
16+
private SmithNumber() {
17+
}
18+
19+
private static int primeFactorDigitSum(int n) {
20+
int sum = 0;
21+
int num = n;
22+
23+
// Factorize the number using trial division
24+
for (int i = 2; i * i <= num; i++) {
25+
while (n % i == 0) { // while i divides n
26+
sum += SumOfDigits.sumOfDigits(i); // add sum of digits of factor
27+
n /= i; // divide n by the factor
28+
}
29+
}
30+
31+
// If n is still > 1, it itself is a prime factor
32+
if (n > 1) {
33+
sum += SumOfDigits.sumOfDigits(n);
34+
}
35+
36+
return sum;
37+
}
38+
39+
/**
40+
* Check if {@code number} is Smith number or not
41+
*
42+
* @param number the number
43+
* @return {@code true} if {@code number} is a Smith number, otherwise false
44+
*/
45+
public static boolean isSmithNumber(int number) {
46+
if (PrimeCheck.isPrime(number)) {
47+
return false; // Smith numbers must be composite
48+
}
49+
50+
return SumOfDigits.sumOfDigits(number) == primeFactorDigitSum(number);
51+
}
52+
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package com.thealgorithms.maths;
2+
3+
import static org.junit.jupiter.api.Assertions.assertFalse;
4+
import static org.junit.jupiter.api.Assertions.assertTrue;
5+
6+
import org.junit.jupiter.params.ParameterizedTest;
7+
import org.junit.jupiter.params.provider.CsvSource;
8+
9+
class SmithNumberTest {
10+
11+
@ParameterizedTest
12+
@CsvSource({"4", "22", "121", "562", "985", "4937775"})
13+
void positiveSmithNumbersTest(int n) {
14+
assertTrue(SmithNumber.isSmithNumber(n));
15+
}
16+
17+
@ParameterizedTest
18+
@CsvSource({"2", "11", "100", "550", "999", "1234557"})
19+
void negativeSmithNumbersTest(int n) {
20+
assertFalse(SmithNumber.isSmithNumber(n));
21+
}
22+
}

0 commit comments

Comments
 (0)