简体   繁体   English

如何在我的代码中使用BigInterger计算素数?

[英]How do I use BigInterger In my code for calculating primes?

I'm using this basic and crude code below for calculating prime numbers then exporting them to a text file: 我使用下面的基本代码和原始代码计算素数,然后将其导出到文本文件:

import java.util.Scanner;
import java.io.*;


public class primeGenerator{

    public static void main(String[] args)throws Exception {
        Scanner kb = new Scanner(System.in);
        String prime;
        long num = kb.nextLong();
        long i;
        long z=0;
        while(z==0){

            for (i=2; i < num ;i++ ){
                long n = num%i;
                if (n==0){

                    break;
                }
            }
            if(i == num){
                writer(num);

            }
            num=num+2;
        }
    }

    public static void writer(long num) throws Exception {

           FileWriter writer = new FileWriter("prime.txt",true); 
           String prime= ""+ num;
           writer.write(prime);
           writer.write("   ");
           writer.flush();
           writer.close();


    }
}

I would like to find primes beyond the Primative long's range and apparently big integer is the way to go about it. 我想找到超出Primitive long范围的素数,显然大整数是解决之道。 So how do i alter my code to do so? 那么我该如何更改我的代码呢?

Do you really need this? 你真的需要这个吗? Having numbers bigger than can be handled by long means you want to test numbers bigger than 9223372036854775807. If your for-loop can test a hundred million divisions per second, it will still take it 2923 years to determine if that number is prime - and longer for larger numbers, of course. 如果数字大于可以长时间处理的数字,则意味着您要测试大于922337203685477575807的数字。如果您的for循环每秒可以测试一亿个除法,则仍然需要2923年的时间才能确定该数字是否为质数,并且更长当然,对于更大的数字。

A common optimization is to only test divisions up to sqrt(num). 常见的优化是仅测试不超过sqrt(num)的除法。 If you haven't found anything then, the number is prime. 如果没有找到任何内容,则该数字为质数。

Well, use BigInteger wherever you've currently got long . 那么,使用BigInteger无论你目前有long Instead of using % you'll use mod , instead of incrementing you'll use i = i.add(BigInteger.ONE) , instead of == 0 you'll use equals(BigInteger.ZERO) etc. 而不是使用%您将使用mod ,而不是增加,而不是i = i.add(BigInteger.ONE) ,而不是== 0,您将使用equals(BigInteger.ZERO)等。

Use Scanner.nextBigInteger instead of Scanner.nextLong , too. 也使用Scanner.nextBigInteger而不是Scanner.nextLong

Given that this looks like homework of some description (possibly self-set, of course) I won't write out the whole code for you - but if you have specific problems, feel free to ask. 考虑到这看起来像是某种描述的作业(当然可能是自定的),我不会为您写出完整的代码-但是,如果您有特定的问题,请随时提出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM