简体   繁体   English

改进第10001个素数项目

[英]Improving 10001st prime number project

I have been working on a Project Euler problem which is to find the 10001st prime number.我一直在研究一个 Project Euler 问题,即找到第 10001 个素数。 I made the project in java and it gave me the correct answer.我用java做了这个项目,它给了我正确的答案。 I couldn't help but notice that it had taken 17 seconds to find the answer.我不禁注意到,找到答案花了 17 秒。 I am fairly new to java and I would appreciate feedback on how to improve the efficiency of my Java program - at the moment it is bruteforce.我对 java 还很陌生,我很感激关于如何提高我的 Java 程序效率的反馈——目前它是蛮力。

static boolean isPrime;  
static int primeCount;  
static int forI = 1;  
static int latestPrime;  

public static void main(String[] args){  
    long startTime = System.currentTimeMillis();  
    while(primeCount < 10001){  
        isPrime = true;  
        forI++;  
        for(int i = forI - 1; i > 1; i--){  
            //If forI is divisible by another number < forI, it is not prime  
            if(forI % i == 0){  
                isPrime = false;  
            }  
        }  
        if(isPrime){  
            primeCount++;  
            latestPrime = forI;  
        }  
    }  
    long endTime = System.currentTimeMillis() - startTime;  
    System.out.println(primeCount+" "+latestPrime);  
    System.out.println("Time taken: " + endTime / 1000 + " seconds");  
}  

You'll want to check out the Sieve of Eratosthenes .你会想看看埃拉托色尼筛

Basically, for each number you are checking whether or not its prime by checking every single number less than it divides it evenly, this is very inefficient.基本上,对于每个数字,您通过检查每个数字小于它的平均数来检查它是否为素数,这是非常低效的。

For an easy improvement, you only need to check all divisors less than the square root of the number.为了轻松改进,您只需检查所有小于数字平方根的除数。

import java.util.Scanner;
public class NewNthPrime{
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        boolean flag = false;
        int max = 10002;
        int[] a = new int[max];
        a[0] = 2;
        int i = 3,j=0;
        int t = in.nextInt();
        for(int a0 = 0; a0 < t; a0++){
            int n = in.nextInt();
            while(j<n){
                for(int y=0;y<a.length;y++){
                    if(a[y]==0){
                        break;
                    }
                    else if (i%a[y]==0){
                        flag = true;
                        break;
                    }
                }
                if(!flag){
                    a[++j]=i;
                }
                flag =false;
                i+=2;
            }
            System.out.println(a[n-1]);
        }
    }
}

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

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