简体   繁体   中英

Why doesn't my program find the 10001st prime? [Project euler-problem7]

My problem is my program doesn't find the 10001st prime. So it never stops and I still don't know the 10001st prime. I will be happy to solve the problem with my implementation. Thank you :)

public class problem7 {

    public static boolean sonuc=true;

    public static void asalmi(int j)
    {
        int counter=0;
        int asayac=0;

        for(int k=1;k<=j;k++)
        {
            if(j%k==0)
            {
                counter++;
            }
        }
        if(counter==2)
        {
            // Only factors are 1 and j, so j is prime
            System.out.println(j);
            asayac++;
            counter=0;
            if(asayac==10001)
            {
                System.out.println(j);
                sonuc=false;
            }
        }
    }

    public static void main(String[] args) 
    {
        int i=1;
        while(sonuc)
        {
            asalmi(i);
            i++;
        }
    }
}

每次调用asalmi时,都将局部变量asayac设置为0。这应该是静态变量,而不是局部变量。

c program to find the 10001st prime number

            #include<stdio.h>
            isPrime(int x){
                int i;
                for(i=2;i<=x/2;i++){
                    if(x%i==0) return 0;
                }
                return 1;
            }
            int main(){
                int n=3;
                int counter=1;
                while(counter!=10001){
                    if(isPrime(n)==1) counter++;
                    n=n+2; // possibility of next prime is by adding 2 to current 
                }
                printf("counter=%d\n",counter);
                printf("number is:%d\n",n-2); //-2 due to unwanted increment in loop

            }

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