@@ -39,12 +39,52 @@ public static boolean isPrime(long n) {
3939 return true ;
4040 }
4141
42+ /**
43+ * Optimized primality check using a mod 30 wheel. This is a balanced generalization of the mod 6
44+ * approach above — by also eliminating multiples of 5, we only test 8 out of every 30 candidates
45+ * (27%) instead of 2 out of every 6 (33%).
46+ *
47+ * <p>The 8 residues coprime to 30 (= 2·3·5) are: 1, 7, 11, 13, 17, 19, 23, 29. Larger wheels
48+ * (mod 210 = 2·3·5·7 with 48 offsets) exist but offer diminishing returns for the added code
49+ * complexity.
50+ */
51+ public static boolean isPrimeWheel30 (long n ) {
52+ if (n < 2 )
53+ return false ;
54+ if (n == 2 || n == 3 || n == 5 )
55+ return true ;
56+ if (n % 2 == 0 || n % 3 == 0 || n % 5 == 0 )
57+ return false ;
58+ long limit = (long ) Math .sqrt (n );
59+ int [] offsets = {1 , 7 , 11 , 13 , 17 , 19 , 23 , 29 };
60+ for (long base = 0 ; base <= limit ; base += 30 )
61+ for (int offset : offsets ) {
62+ long d = base + offset ;
63+ if (d < 7 )
64+ continue ;
65+ if (d > limit )
66+ break ;
67+ if (n % d == 0 )
68+ return false ;
69+ }
70+ return true ;
71+ }
72+
4273 public static void main (String [] args ) {
4374 System .out .println (isPrime (5 )); // true
4475 System .out .println (isPrime (31 )); // true
4576 System .out .println (isPrime (1433 )); // true
4677 System .out .println (isPrime (8763857775536878331L )); // true
4778 System .out .println (isPrime (4 )); // false
4879 System .out .println (isPrime (15 )); // false
80+
81+ System .out .println ();
82+
83+ System .out .println (isPrimeWheel30 (5 )); // true
84+ System .out .println (isPrimeWheel30 (31 )); // true
85+ System .out .println (isPrimeWheel30 (1433 )); // true
86+ System .out .println (isPrimeWheel30 (8763857775536878331L )); // true
87+ System .out .println (isPrimeWheel30 (4 )); // false
88+ System .out .println (isPrimeWheel30 (15 )); // false
4989 }
5090}
0 commit comments