This C program checks whether a given number is prime or not using a recursive approach. A prime number is a positive integer greater than 1 that has no positive integer divisors other than 1 and itself.
Prime numbers are positive integers greater than 1 that have no positive divisors other than 1 and themselves. In other words, a prime number is a number that cannot be evenly divided by any other number except 1 and itself.
Problem Statement
Write a program in C to check if the given number is a prime number or not using Recurssion.
C Program to Check whether a Number is Prime or Not using Recursion
#include <stdio.h>
// Function to check whether a number is prime or not
int isPrime(int num, int i)
{
// Base cases
if (num <= 2)
return (num == 2) ? 1 : 0;
if (num % i == 0)
return 0;
if (i * i > num)
return 1;
// Recursively check for divisibility by subsequent numbers
return isPrime(num, i + 1);
}
int main()
{
int num;
printf("Enter a positive integer: ");
scanf("%d", &num);
// Call the isPrime function
if (isPrime(num, 2))
printf("%d is a prime number.\n", num);
else
printf("%d is not a prime number.\n", num);
return 0;
}
How it works
- The program prompts the user to enter a positive integer.
- The user enters a positive integer
num. - The
mainfunction calls theisPrimefunction with the argumentsnumand2. - The
isPrimefunction is a recursive function that checks whethernumis prime or not. - Inside the
isPrimefunction, there are several base cases and conditions:- If
numis less than or equal to 2, the function returns 1 ifnumis equal to 2 (since 2 is a prime number) or 0 otherwise. - If
numis divisible by the current divisori(whereistarts from 2 and increments in subsequent recursive calls), the function returns 0 (indicating thatnumis not prime). - If
i * iis greater thannum, it means that we have checked divisibility by all possible divisors up to the square root ofnum, and the function returns 1 (indicating thatnumis prime). - If none of the above conditions are met, the function calls itself recursively with an incremented
i.
- If
- The recursion continues until one of the base cases is reached or the conditions for prime checking are met.
- Once the recursion ends, the
mainfunction checks the return value of theisPrimefunction.- If the return value is 1, the program outputs that
numis a prime number. - If the return value is 0, the program outputs that
numis not a prime number.
- If the return value is 1, the program outputs that
- The program terminates.
By using recursion, the program divides the problem of prime number checking into smaller subproblems, recursively checking for divisibility by subsequent numbers. This approach simplifies the logic and avoids the need for a loop.
Input/Output
