简体   繁体   中英

Improving 10001st prime number project

I have been working on a Project Euler problem which is to find the 10001st prime number. I made the project in java and it gave me the correct answer. I couldn't help but notice that it had taken 17 seconds to find the answer. 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.

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]);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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