forked from Algo-Phantoms/Algo-Tree
-
Notifications
You must be signed in to change notification settings - Fork 0
/
smith_number.java
94 lines (79 loc) · 1.73 KB
/
smith_number.java
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/*
* A smith number is a composite number, the sum of whose digits is the
* sum of the digits of its prime factors obtained as a result of prime
* factorization (excluding 1).
*/
import java.util.*;
public class smith_number
{
public void main()
{
Scanner scanner = new Scanner(System.in);
System.out.println("Enter number: ");
int number = scanner.nextInt(); scanner.nextLine();
if(is_smith(number) == true)
{
System.out.println(number+" is a smith number");
}
else
{
System.out.println(number+" is not a smith number");
}
}
boolean is_smith(int number)
{
int sum_prime = 0, i;
for(i = 2; i < number; i++)
{
if(is_prime(i) == true && number % i == 0)
sum_prime += i;
}
if(sum_of_digits(number) == sum_of_digits(sum_prime))
return true;
else
return false;
}
int sum_of_digits(int number)
{
int sum = 0;
while(number != 0)
{
sum += number % 10;
number /= 10;
}
return sum;
}
boolean is_prime(int i)
{
int j, c = 0 ;
for(j = 2; j < i; j++)
{
if(i % j == 0)
{
c++;
break;
}
}
if(c == 0)
return true;
else
return false;
}
}
/*
* Test Cases-
*
* 1.
* Enter number:
* 22
* 22 is a smith number
*
* 2.
* Enter number:
* 21
* 21 is not a smith number
*
* Time Complexity: O(n^3)
* Space Complexity: O(n^3)
* where n is the number of digits in the number input
*/