Smith Number Program in Java (Prime Factor Sum)

⚑ Direct Answer & Key Takeaway

A Smith Number is a composite positive integer whose sum of digits equals the sum of the digits of all its prime factors (counted with multiplicity). For instance, 666 has digit sum 6 + 6 + 6 = 18; its prime factorization is 2 * 3 * 3 * 37, whose digit sum is 2 + 3 + 3 + (3 + 7) = 18. Because prime numbers trivially match their own digit sum, Java programs must exclude primes and 1 before comparing both sums.

1. Why Prime Numbers Are Excluded from Smith Numbers

By definition, a Smith Number must be a composite integer greater than 1. If primes were permitted, every single prime numberβ€”from 2 and 13 up to 997β€”would trivially satisfy the condition because its sole prime factor is the number itself, leaving zero distinction between digit sum and factor digit sum. Likewise, 1 has no prime factors at all, giving a factor digit sum of 0 against a digit sum of 1. Calling isPrime(num) up front and rejecting num <= 1 immediately focuses the algorithm on true composites such as 4, 22, 27, 58, 85, 94, 121, and 666. In ISC board practicals, omitting the composite-number check is one of the fastest ways to lose full correctness marks on hidden prime test cases.

  • Mandatory pre-check: reject 1 and all prime numbers before factoring.
  • Multiplicity rule: sum digits of every prime factor as many times as it divides num.
  • Smallest Smith Numbers: 4, 22, 27, 58, 85, 94, 121, 166, 202, 265, and 666.

2. Prime Factorization Digit-Sum Trace for 666

Tracing num = 666 demonstrates both helper methods and the prime factorization loop cleanly. First, isPrime(666) returns false (divisible by 2), so execution proceeds. Calling sumDigits(666) computes 6 + 6 + 6 = 18 and stores origDigitSum = 18. Next, temp starts at 666, factor starts at 2, and factorDigitSum begins at 0. Since 666 % 2 == 0, factorDigitSum adds sumDigits(2) = 2 (total 2) and temp drops to 333. Now 333 % 2 != 0, so factor advances to 3. Dividing 333 by 3 twice adds sumDigits(3) = 3 twice (total 2 + 3 + 3 = 8) and reduces temp to 37. At factor = 4, 4 * 4 <= 37 checks up through factor = 6 (36 <= 37), then 7 * 7 = 49 > 37 exits the loop. Finally, temp = 37 > 1 adds sumDigits(37) = 3 + 7 = 10, yielding factorDigitSum = 18 == origDigitSum.

  • Original digit sum of 666: 6 + 6 + 6 = 18.
  • Prime factors extracted: 2, 3, 3, and leftover prime 37.
  • Factor digit sum: 2 + 3 + 3 + (3 + 7) = 18 -> Smith Number confirmed.

3. O(sqrt(n)) Factor Loop vs. Naive Division

Stopping the division loop at factor * factor <= temp rather than running while (temp > 1) trims runtime dramatically on composites with a large prime factor. Consider testing num = 2000006 (2 * 1000003): a naive loop incrementing factor from 2 up to 1,000,003 performs one million iterations, whereas stopping at factor * factor <= temp finishes in roughly 1,000 steps because any leftover temp > 1 after exhausting all divisors up to sqrt(temp) must itself be prime. Notice too that factor never needs a separate primality test: since every factor of 2 is divided out before factor reaches 4, and every factor of 3 before 6, no composite integer can ever divide temp. That twin optimization keeps the ISC code concise, fast, and mathematically airtight.

  • Loop invariant: no composite factor can divide temp once all smaller primes are divided out.
  • Leftover prime guard: if (temp > 1) after the loop captures the largest prime factor in O(1).
  • Complexity improves from O(n) worst case to O(sqrt(n)) while keeping code under 50 lines.

4. SmithNumber.java (BlueJ)

import java.util.Scanner;

public class SmithNumber {
    static int sumDigits(int n) {
        int sum = 0;
        while (n > 0) {
            sum += n % 10;
            n /= 10;
        }
        return sum;
    }

    static boolean isPrime(int n) {
        if (n <= 1) {
            return false;
        }
        for (int i = 2; i * i <= n; i++) {
            if (n % i == 0) {
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a positive integer: ");
        int num = sc.nextInt();

        if (num <= 1 || isPrime(num)) {
            System.out.println(num + " is not a Smith Number (must be composite).");
            sc.close();
            return;
        }

        int origDigitSum = sumDigits(num);
        int factorDigitSum = 0;
        int temp = num;
        int factor = 2;

        while (factor * factor <= temp) {
            if (temp % factor == 0) {
                factorDigitSum += sumDigits(factor);
                temp /= factor;
            } else {
                factor++;
            }
        }
        if (temp > 1) {
            factorDigitSum += sumDigits(temp);
        }

        if (origDigitSum == factorDigitSum) {
            System.out.println(num + " is a Smith Number.");
        } else {
            System.out.println(num + " is not a Smith Number.");
        }
        sc.close();
    }
}

Verified Console / Dry-Run Output:

Enter a positive integer: 666
666 is a Smith Number.

Enter a positive integer: 37
37 is not a Smith Number (must be composite).

Enter a positive integer: 24
24 is not a Smith Number.

5. Variable Description Table (VDT) β€” SmithNumber

Variable NameData TypePurpose in Program
scScannerReads the integer candidate from standard input
numintStores the original integer checked for the Smith property
origDigitSumintHolds the sum of digits of num
factorDigitSumintAccumulates the digit sums of all prime factors of num
tempintStores the remaining unfactored quotient during prime division
factorintTests candidate divisors starting from 2 up to sqrt(temp)
🎯 1-on-1 Live Mentorship & Free Study Kit

Excel in ISC Computer Science with 4Achievers Junior

Conquer ISC Computer Science prime-factor algorithms and modular Java design in 1-on-1 or 1:4 Micro-Pods at 4Achievers Junior (Grades 3-12).

πŸ’¬ WhatsApp Now
πŸ”’ Instant WhatsApp notes + free 60-min 1-on-1 trial session
Confirmed! Our Senior Mentor is sending your study kit & free 1-on-1 demo link on WhatsApp now.

6. Common Mistakes & Top Scorer Tips

  • Avoid Mistake: Allowing prime numbers like 2, 3, 5, or 37 to pass as Smith Numbers by omitting the isPrime(num) exclusion check.
  • Avoid Mistake: Adding the prime factor itself (37) instead of sumDigits(factor) (3 + 7 = 10) into factorDigitSum.
  • Avoid Mistake: Stopping the factor loop at factor * factor <= temp without adding sumDigits(temp) for the remaining prime factor when temp > 1.
  • Examiner / Mentor Tip: 666 (the classic textbook example) and 4937775 (Albert Wilansky's brother-in-law's phone number, which named Smith Numbers!) are great viva facts.
  • Examiner / Mentor Tip: Always check your code on a prime number like 37 and on 1 to prove your composite guard triggers properly.
  • Examiner / Mentor Tip: Don't forget the final if (temp > 1) block; without it, semi-primes like 22 (2 * 11) miss their largest prime factor 11.

7. Interactive Concept Check Quiz

Question: Which composite integer below is NOT a Smith Number?

8. Frequently Asked Questions

Why aren't prime numbers like 11 or 37 counted as Smith Numbers?
Every prime number has itself as its sole prime factor, so its digit sum trivially equals its prime-factor digit sum. Mathematicians exclude primes so only interesting composite numbers (like 4, 22, 27, 58, 85, 94, 666) qualify.
Do repeated prime factors get counted once or every time they divide the number?
No, 22 = 2 * 11, where digit sum of 22 is 2 + 2 = 4 and prime factor digit sum is 2 + (1 + 1) = 4. Both 22 and 27 (3 * 3 * 3) are Smith Numbers, whereas 4 is the smallest Smith Number (2 + 2 = 4).
Why doesn't the factor loop need an explicit isPrime(factor) call inside the while loop?
Because every smaller prime factor has already been divided out completely before factor increases, any divisor that divides temp is guaranteed to be prime.

Explore Related Lessons & Free Interactive Tools

Free 1-on-1 Session

Book a Free Demo Class