I wrote this code to find out the next prime number to a user given number.But it is not working as intended.I am a beginner,so any major/minor error/s are possible.Anyone care to find it out please?
#include <iostream>
#include <cmath>
usingnamespace std;
int prime_test(int i);
int main()
{
int x;
cout<<"input a number "<<endl;
cin>>x;
cout<<"the prime number next to "<<x<<" is "<<prime_test(x);
return 0;
}
int prime_test(int i)
{
int z;
while(true)
{
for(int d=2;d<=sqrt(i);d++)
{
if (i%d==0)
continue;
else
z=true;
}
if(z)
return i;
else
i++;
}
}
@ offcutter: you do that by e.g. int z = false;
By the way, int is used for numbers.
So if you only store true or false, you should use bool, as in bool z = false; instead.
A thing to remember later on: try to split your problem into small pieces, that each do simple things.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
bool is_prime(int i)
{
for (int d=2; d <= sqrt(i); ++d) // ++d or d++ has same effect in this case
if (i%d == 0)
returnfalse;
returntrue;
}
int test(int i)
{
while (!is_prime(i)) // while our i isn't a prime,
++i; // increase it
return i;
}
The for loop is wrong. When you find that i%d==0 you know that the number i is not a prime number so you should stop the for loop and set z to false. As it is now you just skip to the next iteration of the for loop.
Only if i%d != 0 for all numbers in the loop you know that i is a prime number. To check this you can set z to true before the for loop. If it's still true afterwards you know that it's a prime number.