Skip to content

Instantly share code, notes, and snippets.

@alabombarda
Created May 28, 2015 19:02
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save alabombarda/f3944cd68dda390d25cb to your computer and use it in GitHub Desktop.
Save alabombarda/f3944cd68dda390d25cb to your computer and use it in GitHub Desktop.
A simple program in C++ that finds the next prime number above a given number.
#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.
*/
@m-f-h
Copy link

m-f-h commented Jun 15, 2022

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!

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