Skip to content

Instantly share code, notes, and snippets.

@m-f-h
Forked from alabombarda/findNextPrime
Last active February 4, 2022 19:57
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save m-f-h/8c81e4014ff9b44abb3440a0f7eb2aa9 to your computer and use it in GitHub Desktop.
Save m-f-h/8c81e4014ff9b44abb3440a0f7eb2aa9 to your computer and use it in GitHub Desktop.
A simple program in C++ that finds the next prime number above a given number.
// findNextPrime.cpp - return the next larger prime number
// (input taken from command line args or from stdin)
#include <iostream>
int findNextPrime(int n); // given a number n, find the next larger prime number above n
bool isPrime(int n); // given a number n, determine whether it is prime
int main(int argc, char**argv)
{
int input;
if( argc > 1 ) input = atoi(argv[1]);
else {
std::cout << "Please enter a 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 + (n & 1 && n > 1 || !n ? 2 : 1); // start at n+2 for odd n>1 or n=0, else n+1
while (!isPrime(nextPrime))
nextPrime += 2;
return nextPrime;
}
// given a number n, determine if it is prime
bool isPrime(int n)
{
if ( (n&1)==0 ) return n==2; // if even, then false unless n==2
// loop over odd trial divisors from 3 to sqrt(n) to check for factors
for (int i = 3; i*i <= n; i += 2)
{
if (n % i == 0) // found a factor that isn't 1 or n, therefore not prime
return false;
}
return n>1; // prime unless n=1 (no divisors > 1 but not prime)
}
/*
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.
*/
@m-f-h
Copy link
Author

m-f-h commented May 7, 2020

Simplified findNextPrime() to scan only odd numbers (if n > 1), isPrime to check only odd divisors < sqrt(n).

@m-f-h
Copy link
Author

m-f-h commented May 7, 2020

added use of cmd line arg ; changed "enter prime" to "enter number" ; fixed findNextPrime(n=0) .

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment