Hi guys.
I have a homework which is to find the nearest prime number to the number N you input. And i have managed to code one but it's unstable. Somtimes it works but not always.
#include <iostream>
#include <cmath>
usingnamespace std;
int main ()
{
int n,i=2,j,kq=0,a,mn=0,t=2,b,k;
cout << "Pleas input n"<< endl;
cin >> n;
j=n-1;
k=n+1;
while (j<n&&j>0) //this is to search the nearest prime from the left side of n
{
kq=0;
i=2;
while (i<=pow(j,0.5))
{
if (j%i==0)
{
i=2; //if kq remains zero after the whole loop then the
kq++; //current j is a prime number since it's not
break; //divisible for any numbers from 2 to sqrt(j)
}
i++;
}
if (kq==0)
{
break;
}
--j;
}
while (k>n) // this is for the right side of n
{
mn=0;
t=2;
k=n+1;
while (t<=pow(k,0.5))
{
if (k%t==0)
{
t=2; // mn is the same as kq
mn++;
break;
}
t++;
}
if (mn==0)
{
break;
}
++k;
}
if ((n-j)<(k-n)) // if the distance from n to the j is smaller than
cout << j << endl; // the distance from n to k then we print out n
if ((n-j)>(k-n)) // and the other way aroumd. if they are equal
cout << k << endl; // then print out both.
if ((n-j)==(k-n))
cout << j << " " << k << endl;
return 0;
}
It works when i enter number like 6, 10, 12, 14, 40, etc
but it does not work when i enter prime number for the beginning and some specific number like 14,20,44,80,...
Can you point out what is wrong with my code. Thank you.
make a function: bool isPrime(int arg) which returns true if the argument is prime.
then send j and k until return value is true, start with j=n; k=n+1; j--; k++;
I think anup30 is trying to help you simplify your code and make it a lot easier for you do find the problems on your own. So many loops with break statements, and repeating the same process multiple times along the way can be difficult to debug.
Non-descriptive variables make it much harder to analyze your code, too. How many times have you asked yourself what i, kq, mn, m, etc. . . really mean in the program?
Back when our computers were limited to 48k (Kilobytes) of memory, cryptic variable names mattered - "Number" took six bytes where "N" only took one. But nowadays, thankfully, we aren't limited that way.
anup30, again I really appreciate your help! I was very persistent back then. I was very frustrated because of this code. Yeah it's SUPER complicated for no reason. I will do it your way and simpify it. Thank you for helping me so much!!