Advertisement
Guest User

mersenne.java

a guest
Feb 14th, 2018
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.34 KB | None | 0 0
  1. import java.math.BigInteger;
  2. public class Mersenne
  3. {
  4.  
  5.     public static boolean isPrime(int p) {
  6.         if (p == 2)
  7.             return true;
  8.         else if (p <= 1 || p % 2 == 0)
  9.             return false;
  10.         else {
  11.             int to = (int)Math.sqrt(p);
  12.             for (int i = 3; i <= to; i += 2)
  13.                 if (p % i == 0)
  14.                     return false;
  15.             return true;
  16.         }
  17.     }
  18.  
  19.     public static boolean isMersennePrime(int p) {
  20.         if (p == 2)
  21.             return true;
  22.         else {
  23.             BigInteger m_p = BigInteger.ONE.shiftLeft(p).subtract(BigInteger.ONE);
  24.             BigInteger s = BigInteger.valueOf(4);
  25.             for (int i = 3; i <= p; i++)
  26.                 s = s.multiply(s).subtract(BigInteger.valueOf(2)).mod(m_p);
  27.             return s.equals(BigInteger.ZERO);
  28.         }
  29.     }
  30.  
  31.     // an arbitrary upper bound can be given as an argument
  32.     public static void main(String[] args) {
  33.         int upb;
  34.         if (args.length == 0)
  35.             upb = 500;
  36.         else
  37.             upb = Integer.parseInt(args[0]);
  38.  
  39.         System.out.print(" Finding Mersenne primes in M[2.." + upb + "]:\nM2 ");
  40.         for (int p = 3; p <= upb; p += 2)
  41.             if (isPrime(p) && isMersennePrime(p))
  42.                 System.out.print(" M" + p);
  43.         System.out.println();
  44.     }
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement