Search⌘ K
AI Features

Solution Review 2: Check for Prime Number

Explore how to implement a recursive function in C++ to check for prime numbers. Understand the role of base cases and recursive calls while iterating through factors, improving your skills in recursion with numbers.

C++
#include <iostream>
using namespace std;
bool isPrime(int n, int i)
{
// first base case
if (n<2)
{
return 0;
}
// second base case
if(i==1)
{
return 1;
}
// third base case
if (n%i==0)
{
return 0;
}
// recursive case
else
{
isPrime(n,i-1);
}
}
int main() {
int input= 13;
bool result= isPrime(input,input/2);
// prints if number is prime
if (result==1)
{
cout<<input<<" is a prime number.";
}
//prints if number is not prime
else
{
cout<<input<<" is a not a prime number.";
}
}

Understanding the Code

In the code above, the function isPrime is a recursive ...