Skip to content

Commit 1f5b521

Browse files
committed
Completed "Carmichael Numbers"
1 parent 4dac2ac commit 1f5b521

File tree

1 file changed

+44
-40
lines changed

1 file changed

+44
-40
lines changed
Lines changed: 44 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -1,60 +1,64 @@
11
package Challenges_VII.Carmichael_Numbers;
22

3-
import java.math.BigInteger;
4-
import java.util.HashMap;
53
import java.util.Scanner;
64

75
public class Main {
8-
6+
97
public static final int MAX = 65001;
10-
public static HashMap<String,Integer> primeHash;
118

129
public static void main(String[] args) {
1310
Scanner s = new Scanner(System.in);
14-
primeHash = new HashMap<String, Integer>();
1511
int next;
16-
genPrimes();
17-
18-
while((next = s.nextInt()) != 0){
19-
BigInteger randNum = BigInteger.valueOf((int) (Math.random() * (next - 1)) + 2);
20-
BigInteger fermatTest = randNum.pow(next).mod(BigInteger.valueOf(next));
21-
if(fermatTest.equals(randNum) && primeHash.get(String.valueOf(next)) == null){
12+
13+
while ((next = s.nextInt()) != 0) {
14+
boolean isCar = true;
15+
if (checkPrime(next))
16+
isCar = false;
17+
else{
18+
//check a^b mod b for every value from 2 to 'next'
19+
for (int i = 2; i < next; i++) {
20+
if (powerMod(i, next, next) != i) {
21+
isCar = false;
22+
break;
23+
}
24+
}
25+
}
26+
27+
if (isCar)
2228
System.out.println("The number " + next + " is a Carmichael number.");
23-
}else{
29+
else
2430
System.out.println(next + " is normal.");
25-
}
2631
}
32+
2733
s.close();
2834
System.exit(0);
2935

3036
}
31-
32-
33-
public static void genPrimes(){
34-
35-
boolean[] sieve = new boolean[MAX+1];
36-
sieve[0] = true;
37-
sieve[1] = true;
38-
sieve[2] = false;
39-
40-
for(int i = 4; i <= MAX; i+=2)
41-
sieve[i] = true;
42-
43-
for(int i = 3; i < (int)Math.sqrt(MAX)+1; i+=2)
44-
{
45-
if(!sieve[i])
46-
{
47-
for(int j = i*i; j <= MAX; j+=i)
48-
sieve[j] = true;
49-
}
50-
}
51-
52-
for(int b = 0; b < sieve.length; b++){
53-
if(!sieve[b]){
54-
primeHash.put(String.valueOf(b), b);
55-
}
56-
}
5737

58-
}
38+
public static boolean checkPrime(int num) {
39+
if (num % 2 == 0)
40+
return false;
41+
42+
for (int i = 3; i <= (int) Math.sqrt(num); i += 2) {
43+
if (num % i == 0)
44+
return false;
45+
}
46+
47+
return true;
48+
}
49+
50+
51+
public static int powerMod(long a, long b, long m) {
52+
long result = 1;
53+
while(b > 0) {
54+
if (b % 2 == 1)
55+
result = (result * a) % m;
56+
57+
b /= 2;
58+
a = (a * a) % m;
59+
}
60+
return (int) result;
61+
}
62+
5963

6064
}

0 commit comments

Comments
 (0)