Write a program that finds all Mersenne prime with p<=31 and displays the output as follows:
p 2^p-1
2 3
3 7
5 31
...
public class C1 { public static void main(String[] args) { int number = 2; System.out.print("p "); System.out.println("2^p-1"); while(number <= 31) { int newnumber = (int)Math.pow(2, number) - 1;//計算2^p-1 boolean a = isMersennePrimesNumber(newnumber); if(a == true) { System.out.print(number + " "); System.out.println(newnumber); } number ++ ; } } public static boolean isMersennePrimesNumber(int number) { boolean bool = false ; int remainder = 0; int factor = 0 ; for(int i = 1 ; i <= number ; i++)//計算此數的因數個數 { remainder = number % i; if(remainder == 0) { factor = factor + 1; } } if(factor == 2) { bool = true ; remainder = 0; factor = 0 ; } else if(factor != 2) { bool = false ; remainder = 0; factor = 0 ; } return bool ; } }
沒有留言:
張貼留言