java BigInteger类的运用

  • 找出所有素数2^p-1(p<=100)
  • long无法实现,采用BigInteger类来实现
  • PS:类的多少个人习惯
import java.math.BigInteger; 
public class mainClass1 {
 	public static void main(String[] args) {
 		// TODO 自动生成的方法存根		
 		BigInteger a = new BigInteger("2");	//大数字赋值 a = 2,不能直接	BigInteger a = 2
 		BigInteger b = new BigInteger("1");		
 		for(int i = 2;i <= 100; i++){			
 			a = a.pow(i);	//大整数a = a^i		
 			if(mersenne.isPrime(a.subtract(b))) //大数字a-b				
 				System.out.print(i + " ");		
 		} 	
 	} 
 }  
import java.math.BigInteger;  
public class mersenne {	
	public static boolean isPrime(BigInteger z){ 
		BigInteger m = new BigInteger("2");		
		BigInteger n = new BigInteger("0");		
		for(;z.compareTo(m.multiply(m)) > 0; m.add(n)){	//大数字 (;z > m*m ; m = m+n)		
			BigInteger[] arr=z.divideAndRemainder(m);    //取除数arr[0]和余数arr[1]						
			if(arr[1].compareTo(n) == 0)return false;		
		}		
		return true;	
	}
}
发布了33 篇原创文章 · 获赞 2 · 访问量 6957

猜你喜欢

转载自blog.csdn.net/qq_42677329/article/details/89395088