0% found this document useful (0 votes)
22 views

Isc Computer Project #2

Uploaded by

Rahul Ganguly
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Isc Computer Project #2

Uploaded by

Rahul Ganguly
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

Program 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

Step 3: In main method, Input n from user


Step 4: Set long p=0, n1=n, i=2
Step 5: Set String s=””
Step 6: Set while loop with condition (n>1)

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

Step 7: If sum(n1) = sum(p), print “It is a Smith Number” else


print “It is not a Smith Number”
Step 8: END

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

public static void main(String[] args)


{

Scanner sc = new Scanner(System.in);


System.out.print("Enter a number: ");
long n = sc.nextLong();

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:

Variable Name Data Type Description


n long Stores input from user
Stores all prime numbers as a
p long
single no.
Stores values of a prime
i long
number
n1 long Stores value of n
s String Converts number to string
m long Receives a number
sum long Stores sum of each digit

Sample Input / Output:

You might also like