|
| 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 | +} |
0 commit comments