|
1 | 1 | package Challenges_VII.Carmichael_Numbers;
|
2 | 2 |
|
3 |
| -import java.math.BigInteger; |
4 |
| -import java.util.HashMap; |
5 | 3 | import java.util.Scanner;
|
6 | 4 |
|
7 | 5 | public class Main {
|
8 |
| - |
| 6 | + |
9 | 7 | public static final int MAX = 65001;
|
10 |
| - public static HashMap<String,Integer> primeHash; |
11 | 8 |
|
12 | 9 | public static void main(String[] args) {
|
13 | 10 | Scanner s = new Scanner(System.in);
|
14 |
| - primeHash = new HashMap<String, Integer>(); |
15 | 11 | 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) |
22 | 28 | System.out.println("The number " + next + " is a Carmichael number.");
|
23 |
| - }else{ |
| 29 | + else |
24 | 30 | System.out.println(next + " is normal.");
|
25 |
| - } |
26 | 31 | }
|
| 32 | + |
27 | 33 | s.close();
|
28 | 34 | System.exit(0);
|
29 | 35 |
|
30 | 36 | }
|
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 |
| - } |
57 | 37 |
|
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 | + |
59 | 63 |
|
60 | 64 | }
|
0 commit comments