-
-
Save alabombarda/f3944cd68dda390d25cb to your computer and use it in GitHub Desktop.
#include <iostream> | |
int findNextPrime(int n); //given a number n, find the next closest prime number above n | |
bool isPrime(int n); //given a number n, determine if it is prime | |
int main() | |
{ | |
int input; | |
std::cout << "Please enter a prime number: "; | |
std::cin >> input; | |
std::cout << "\nThe next prime number after " << input << " is " << findNextPrime(input) << ". \n"; | |
} | |
//given a number n, find the next closest prime number above n | |
int findNextPrime(int n) | |
{ | |
int nextPrime = n; | |
bool found = false; | |
//loop continuously until isPrime returns true for a number above n | |
while (!found) | |
{ | |
nextPrime++; | |
if (isPrime(nextPrime)) | |
found = true; | |
} | |
return nextPrime; | |
} | |
//given a number n, determine if it is prime | |
bool isPrime(int n) | |
{ | |
//loop from 2 to n/2 to check for factors | |
for (int i = 2; i <= n/2; i++) | |
{ | |
if (n % i == 0) //found a factor that isn't 1 or n, therefore not prime | |
return false; | |
} | |
return true; | |
} | |
/* | |
SAMPLE OUTPUT | |
Please enter a prime number: 6 | |
The next prime number after 6 is 7. | |
Please enter a prime number: 10 | |
The next prime number after 10 is 11. | |
Please enter a prime number: 11 | |
The next prime number after 11 is 13. | |
Please enter a prime number: 788 | |
The next prime number after 788 is 797. | |
*/ |
as I said 1 yr ago...
FWIW, I made these improvements (only odd trial divs <= sqrt(n), also use of cmd line argv[1] if given) in a fork, see https://gist.github.com/m-f-h/8c81e4014ff9b44abb3440a0f7eb2aa9
(I'm new to Gist, don't know whether/how it's possible to propose to merge with this...)
for loop in isPrime():
To save time and complexity you can use this
for (int i = 2; i * i <= n; ++i) is enough
I don't know why you say the same thing than @majorli on May 2020.
What is worse, it seems my improvement from May 2020:
check parity and then " for (int i = 3; i * i <= n; i+=2) ",
(please see here: https://gist.github.com/m-f-h/8c81e4014ff9b44abb3440a0f7eb2aa9 )
which makes it twice as fast, apparently didn't make it's way in :-( .
Do I have to do some "commit" / merge request? if so, how?
(I don't see any button or link to do that on the page where I see my improved version, i.e., the above link.)
Thanks and hope that helps!
the for loop in isPrime(): for (int i = 2; i * i <= n; ++i) is enough