I've written a function in C++ to find the closest prime number after the input number. Let's assume the input number is larger than 100, so there is no special check for the cases when the input number is 1 or 2 or etc.
int getClosestPrime(int inputNum){
bool isPrime = false;
inputNum++;
while (!isPrime){
for (int i = 2; i <= inputNum/2; i++){
if (inputNum % i == 0){
isPrime = false;
break; //if at any time found it's not a prime, break the for loop
}
isPrime = true;
}
if (isPrime == false){
inputNum++;
} else {
return inputNum;
}
}
}
I think the logic should be good enough as I tested here on ideone: https://ideone.com/hcUpvK it's giving the right results.
However, when I use Xcode to run the code, it always complains that "Control may reach end of non-void function".
Could anybody explain? Thanks!