I made a code to determine whether a number is prime or not. I doubt it's optimized, but that's not what's interesting. Thing is, this code works for numbers up to around 10^7, with 10^9 being described as a prime number which it obviously isn't. Thoughts on reason?
#include "../std_lib_facilities.h" //include definitions
int main()
{
int n = 1;
int x = 2; //x starts at 2 because prime numbers are all div. by 1
cout << "enter a number\n";
cin >> n;
if (n % 2 == 0 || n % 3 == 0) // number divisible by 2 or 3?
{
cout << "not prime number\n";
keep_window_open();
return 0;
}
else
{
if (n % 5 == 0 || n % 7 == 0) // number divisible by 5 or 7?
{
cout << "not prime number\n";
keep_window_open();
return 0;
}
else
{
while (x < n) //check if divisible by all numbers below
{
if (n % x == 0)
{
cout << "not prime number\n";
keep_window_open();
return 0;
}
else
{
x++;
}
}
cout << "prime number\n";
keep_window_open();
return 0;
}
}
}
tl:dr for code: check if number divisible by 2 or 3, then by 5 or 7, then if number passes all those check all numbers beneath it. If it passes that, print that it's a prime number.
C:\Users\Michael\Programming\cplusplus.com\random\p2>a
enter a number
1000000000
not prime number
C:\Users\Michael\Programming\cplusplus.com\random\p2>a
enter a number
1000000007
prime number
Have you considered any overflow problems?
BTW, you can significantly decrease the amount of time it takes by checking
Thank you for the pointing out the sqrt possibility, I forgot about that.
10^10 causes the prime number thing my bad didn't count the zeroes properly.
And I guess it's overflow-that explanation makes sense. Thank you.