In Trial by Division, and most other ways of finding a prime number, you need TWO for loops, not counting the for loop to print them out.
Your code only has ONE for loop.
Did you notice that the code I posted had TWO for loops? :
Code:
For every N in the set of numbers: {
good=1
get the sqrRoot of N
for(i=3;i<sqrRoot;i+=2) { //after 2 all primes are odd
if(N mod i ==0) {
good=0;
break;
}
}
if(good) {
the number is prime.
add it to the primesArray[]
}
}
N represents the Number being tested to see if it's prime. i is in the loop that generates the numbers that will be used to test N, by the modulus operator ( % ), to see if it will divide evenly into N.
If you can find every prime number, then you should look over that code. Because what you are doing here, is searching for every prime number between n and 2n EXCEPT, you will stop your search, when you have found your first prime.
That means your outer for loop will not start at N=2. It will start at the number that the user enters for n, and will stop at 2n, or before.
So in your code, let's see what it still needs:
Code:
printf("prime numbers:");
//adjust an even numbered n, to make it odd
if(n%2==0)
++n;
//add the second for loop here:
for(N=n;N<2*n;N+=2) { //all numbers to be tested, will now be odd
a=sqrt(N); //delete your other sqrt() code above this
for(i=3;i<=a;i+=2) //need <= here All testing numbers will also be odd
{
if (N%i==0) { //you're testing N, not n here
y=0;
break;
}
if (y)
{
c[t]=i;
t++;
}
}
If you only want ONE prime number between n and 2n, then if (y) should print out the prime number you have just found, and return (end the program). You're done.
Put those changes into your program, and see how it does. I have not tried to run it. It's at least "close", however.