![]() |
VOOZH | about |
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.
Table of Content
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:
true
Time Complexity:O(√n log n), √n for factorization and log n for digit sum operations
Auxiliary Space:O(1)
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.
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.
true
Time Complexity: O(n log logn)
Space Complexity: O(n)