Isc Computer Project #2
Isc Computer Project #2
Question: Write a program in Java to enter a number and check whether it is a Smith number
or not. A Smith number is a composite number, whose sum of the digits is equal to the sum of
its prime factors. 4, 22, 27, 58, 85, 94, 121… are Smith numbers.
Eg: 85 = 17x5
(8+5) = 13 and (5+1+7) = 13
Algorithm:
Step 1: Start
Step 2: Create a static method sum(long n) which returns a long value
Sub-Steps:
2.1: Initialize sum
2.2: Set while-loop with condition (m>0),
set sum = sum + n%10 and set m = m/10
2.3: Return sum
Sub-Steps:
6.1: If(n%i)=0, set s = “”+i, p=p+(long)Math.pow(10,s.length),
and n = n/I, else increase i by 1
Source code:
import java.util.Scanner;
class Smith
{
static long sum(long m) {
long sum = 0;
while (m > 0) {
sum += m % 10; // Calculates sum of digits of received no.
m /= 10;
}
return sum;
} //end of method
long p = 0, n1 = n, i = 2;
String s = "";
while (n > 1)
if (n % i == 0) {
s = "" + i;
p = p * (long) Math.pow( 10, s.length() ) + i;
n /= i; //concats all prime factors as a single number
} else
i++;
if (sum(n1) == sum(p))
System.out.print("It is a Smith Number");
else
System.out.print("It is not a Smith Number");
} //end of main
} //end of class
Variable Description: