【问题标题】:How to make primality test accept large numbers如何使素数测试接受大数
【发布时间】:2019-10-22 18:15:27
【问题描述】:

我有一个接受最多 10 位整数的素数测试代码,但我想扩展它,以便代码接受超过 200 位数字。我应该在代码中切换什么?

import java.util.*; 
import java.math.*; 

class CheckPrimeTest { 

    static boolean checkPrime(long n) 
    { 
        // Corner case 
        if (n <= 1) return false; 

        // Check from 2 to n-1 
        for (int i = 2; i < n; i++) 
            if (n % i == 0) 
                return false; 

        return true; 
    } 

    // Driver Program  
    public static void main(String args[]) 

                         throws java.lang.Exception 
    { 
 Scanner input = new Scanner(System.in);
  System.out.print("Enter an integer: ");
        long n = input.nextInt();  

       System.out.println(checkPrime(n)); 

    } 
} 

【问题讨论】:

标签: java primality-test


【解决方案1】:

如果你有这么大的数字,你不能使用ints 和longs,你将不得不使用BigInteger,它已经为你定义了一个isProbablePrime 方法:

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    BigInteger integer = new BigInteger(scanner.nextLine());
    System.out.println(integer.isProbablePrime(1));
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-19
    相关资源
    最近更新 更多