Skip to content

Commit 8ee51ed

Browse files
committed
Smith Number
1 parent 8228c41 commit 8ee51ed

File tree

1 file changed

+91
-0
lines changed

1 file changed

+91
-0
lines changed
Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
package com.java.numbers;
2+
3+
import java.util.ArrayList;
4+
import java.util.Scanner;
5+
6+
/*
7+
* Smith Number
8+
*
9+
* A Smith number is a composite number
10+
* the sum of whose digits is the sum of
11+
* the digits of its prime factors (excluding 1)
12+
*
13+
* Say given number is 22
14+
* prime factors of 22 are
15+
* 2, 11
16+
*
17+
* sum of digits of 22 = 4
18+
* sum of digits of prime factors
19+
* 2 * 11 = 2 + 1 + 1 = 4
20+
*
21+
* given number is 27
22+
* prime factors = 3, 3, 3
23+
* sum of digits of 27 = 2+7 = 9
24+
* sum of digits of prime factors
25+
* 3+3+3 = 9
26+
*
27+
* Other examples are
28+
* 4, 22, 27, 58, 85, 94, 121, 166, 202, 265
29+
*/
30+
public class SmithNumber {
31+
public static void main(String[] args) {
32+
Scanner scanner = new Scanner(System.in);
33+
System.out.println("Enter any positive integer :: ");
34+
int num = Integer.parseInt(scanner.nextLine().trim());
35+
36+
if(sumOfDigits(num) == getPrimeFactorsDigitSum(num))
37+
System.out.println("Given number : "+num+" is a Smith Number");
38+
else
39+
System.out.println("Given number : "+num+" is NOT a Smith Number");
40+
scanner.close();
41+
}
42+
43+
private static int getPrimeFactorsDigitSum(int n){
44+
int sum =0;
45+
ArrayList<Integer> primeFactors = getPrimeFactors(n);
46+
for(int v : primeFactors)
47+
sum += sumOfDigits(v);
48+
return sum;
49+
}
50+
51+
private static ArrayList<Integer> getPrimeFactors(int n){
52+
ArrayList<Integer> factors = new ArrayList<>();
53+
int len = (int) Math.sqrt(n);
54+
for(int i=2; i<= len;i++){
55+
while( n%i == 0 ){
56+
factors.add(i);
57+
n = n/i;
58+
}
59+
}
60+
if( n > 2 )
61+
factors.add(n);
62+
System.out.println("Prime Factors are : "+factors);
63+
return factors;
64+
}
65+
66+
private static int sumOfDigits(int n){
67+
int sum = 0;
68+
while( n > 0 ){
69+
int digit = n % 10;
70+
sum += digit;
71+
n = n / 10;
72+
}
73+
return sum;
74+
}
75+
}
76+
/*
77+
OUTPUT
78+
79+
Enter any positive integer :: 22
80+
Prime Factors are : [2, 11]
81+
Given number : 22 is a Smith Number
82+
83+
Enter any positive integer :: 85
84+
Prime Factors are : [5, 17]
85+
Given number : 85 is a Smith Number
86+
87+
Enter any positive integer :: 150
88+
Prime Factors are : [2, 3, 5, 5]
89+
Given number : 150 is NOT a Smith Number
90+
91+
*/

0 commit comments

Comments
 (0)