- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.java
More file actions
Latest commit
64 lines (53 loc) · 1.46 KB
/
Copy pathMain.java
File metadata and controls
64 lines (53 loc) · 1.46 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
/*
@author: mc-es
Problem 35
The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime.
There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97.
How many circular primes are there below one million?
Answer: 55
*/
publicclassMain {
publicstaticvoidmain(String[] args) {
intcount = 4; // 2, 3, 5, and 7 are already considered.
for (intn = 11; n < 1000000; n += 2) {
if (Integer.toString(n).matches(".*[024568].*")) {
continue;
}
if (isCircularPrime(n)) {
count++;
}
}
System.out.println(count);
}
// Determines whether a number is prime or not
publicstaticbooleanisPrime(intn) {
if (n < 2) {
returnfalse;
}
for (inti = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
returnfalse;
}
}
returntrue;
}
// Returns the number obtained by rotating the digits of the input number
publicstaticStringrotate(intn) {
Strings = Integer.toString(n);
returns.substring(1) + s.charAt(0);
}
// Determines whether a number is circular prime or not
publicstaticbooleanisCircularPrime(intn) {
if (!isPrime(n)) {
returnfalse;
}
Stringrotated = rotate(n);
while (!rotated.equals(Integer.toString(n))) {
if (!isPrime(Integer.parseInt(rotated))) {
returnfalse;
}
rotated = rotate(Integer.parseInt(rotated));
}
returntrue;
}
}