Mersenne primes: Difference between revisions
Content added Content deleted
(GP) |
(Added Java) |
||
Line 85: | Line 85: | ||
2 ^ 19 - 1 |
2 ^ 19 - 1 |
||
2 ^ 31 - 1</pre> |
2 ^ 31 - 1</pre> |
||
=={{header|Java}}== |
|||
{{trans|Kotlin}} |
|||
<lang Java>import java.math.BigInteger; |
|||
public class MersennePrimes { |
|||
private static final int MAX = 20; |
|||
private static final BigInteger ONE = BigInteger.ONE; |
|||
private static final BigInteger TWO = BigInteger.valueOf(2); |
|||
private static boolean isPrime(int n) { |
|||
if (n < 2) return false; |
|||
if (n % 2 == 0) return n == 2; |
|||
if (n % 3 == 0) return n == 3; |
|||
int d = 5; |
|||
while (d * d <= n) { |
|||
if (n % d == 0) return false; |
|||
d += 2; |
|||
if (n % d == 0) return false; |
|||
d += 4; |
|||
} |
|||
return true; |
|||
} |
|||
public static void main(String[] args) { |
|||
int count = 0; |
|||
int p = 2; |
|||
while (true) { |
|||
BigInteger m = TWO.shiftLeft(p - 1).subtract(ONE); |
|||
if (m.isProbablePrime(10)) { |
|||
System.out.printf("2 ^ %d - 1\n", p); |
|||
if (++count == MAX) break; |
|||
} |
|||
// obtain next prime, p |
|||
while (true) { |
|||
p = (p > 2) ? p + 2 : 3; |
|||
if (isPrime(p)) break; |
|||
} |
|||
} |
|||
} |
|||
}</lang> |
|||
{{out}} |
|||
<pre>2 ^ 2 - 1 |
|||
2 ^ 3 - 1 |
|||
2 ^ 5 - 1 |
|||
2 ^ 7 - 1 |
|||
2 ^ 13 - 1 |
|||
2 ^ 17 - 1 |
|||
2 ^ 19 - 1 |
|||
2 ^ 31 - 1 |
|||
2 ^ 61 - 1 |
|||
2 ^ 89 - 1 |
|||
2 ^ 107 - 1 |
|||
2 ^ 127 - 1 |
|||
2 ^ 521 - 1 |
|||
2 ^ 607 - 1 |
|||
2 ^ 1279 - 1 |
|||
2 ^ 2203 - 1 |
|||
2 ^ 2281 - 1 |
|||
2 ^ 3217 - 1 |
|||
2 ^ 4253 - 1 |
|||
2 ^ 4423 - 1</pre> |
|||
=={{header|Julia}}== |
=={{header|Julia}}== |