VOOZH about

URL: https://www.geeksforgeeks.org/dsa/smith-number/

⇱ Smith Number - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Smith Number

Last Updated : 11 May, 2026

Given a number n, the task is to find out whether this number is a Smith number or not. A Smith number is a compositenumber whose sum of digits is equal to the sum of digits of its prime factorization.

Examples:

Input: n = 648
Output: true
Explanation: 648 = 23*34, 6+4+8 = 2+2+2+3+3+3+3. 
and since 648 is a composite number, 648 is a Smith number.

Input: n = 762
Output: true
Explanation: 762 = 21*31*1271 is a Smith number since 7+6+2 = 2+3+(1+2+7).
and it is a composite number.

Using Prime Factorization - O(√n log n) Time O(1) Space

Compute the sum of digits of the number and compare it with the sum of digits of its prime factors (including multiplicity); if both are equal and the number is not prime, it is a Smith Number.

Algorithm:

  • First, calculate the sum of digits of the given number.
  • Then, find all its prime factors using trial division.
  • Add the digit sum of each prime factor (including repetitions).
  • If the number is prime, return 0.
  • Finally, compare both sums; if equal return 1, otherwise return 0.

Output
true

Time Complexity:O(√n log n), √n for factorization and log n for digit sum operations
Auxiliary Space:O(1)

Efficient Approach for Multiple Queries using Sieve - O(n log ⁡log⁡ n) Time O(n) Space

The idea is to compare the sum of digits of the number with the sum of digits of its prime factors. We first compute the Least Prime Factor (LPF) using a sieve to enable fast factorization. Then, we find the digit sum of the number and its prime factors (using LPF). If both sums are equal, the number is a Smith Number; otherwise, it is not.

Why this works efficiently:

This approach is efficient because the Least Prime Factor (LPF) array is precomputed once using a sieve in O(n log log n) time, which allows fast reuse for multiple queries. Using LPF, prime factorization of any number is reduced to O(log n) time by repeatedly dividing by the smallest prime factor. It also eliminates repeated prime checks, since all smallest prime factors are already stored. Additionally, computing the digit sum is a lightweight operation, adding only O(log n) overhead, making the overall process fast and scalable.


Output
true

Time Complexity: O(n log ⁡log⁡n)
Space Complexity: O(n)

Comment
Article Tags: