-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSmithNumber.java
More file actions
78 lines (78 loc) · 1.79 KB
/
SmithNumber.java
File metadata and controls
78 lines (78 loc) · 1.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import java.util.*;
public class SmithNumberExample1
{
//function finds the sum of digits of its prime factors
static int findSumPrimeFactors(int n)
{
int i=2, sum=0;
while(n>1)
{
if(n%i==0)
{
sum=sum+findSumOfDigit(i);
n=n/i;
}
else
{
do
{
i++;
}
while(!isPrime(i));
}
}
//returns the sum of digits of prime factors
return sum;
}
//function finds the sum of digits of the given numbers
static int findSumOfDigit(int n)
{
//stores the sum
int s=0;
while(n>0)
{
//finds the last digit of the number and add it to the variable s
s=s+n%10;
//removes the last digit from the given number
n=n/10;
}
//returns the sum of digits of the number
return s;
}
//function checks if the factor is prime or not
static boolean isPrime(int k)
{
boolean b=true;
int d=2;
while(d<Math.sqrt(k))
{
if(k%d==0)
{
b=false;
}
d++;
}
return b;
}
//driver code
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
//reads an integer from the user
int n=sc.nextInt();
//calling the user-defined function that finds the sum of digits of the given number
int a = findSumOfDigit(n);
//calling the user-defined function that finds the sum of prime factors
int b = findSumPrimeFactors(n);
System.out.println("Sum of Digits of the given number is = "+a);
System.out.println("Sum of digits of its prime factors is = "+b);
//compare both the sums
if(a==b)
//prints if above condition returns true
System.out.print("The given number is a smith number.");
//prints if above condition returns false
else
System.out.print("The given number is not a smith number.");
}
}