Reputation: 127
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++;
}
}
}
Upvotes: 0
Views: 83
Reputation: 509
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
}
Upvotes: 0
Reputation: 2689
Every time you call asalmi, you set a local variable asayac to 0. This should be a static variable, not a local one.
Upvotes: 2