Signup/Sign In
PUBLISHED ON: JANUARY 24, 2022

C Program to find whether a Number is Prime or Not using Recursion

learn C language tutorial

Logic To Find Whether A Number Is Prime Or Not Using Recursion:

  • Get the input from the user and store it in num1 variable, The integer has no integral factor is called a prime number,
  • The primenum() is called by another variable check by passing the num1 value, the value of num1 is divided by 2 as an argument,
  • The function is used to find whether the given number is prime or not, the if-else condition is used to check the value of i, if i=1 returns the value of 'i' to check variable to call the function,
  • else the function is called by passing the value of num1 variable & decrement the value by 1, returns the value to check variable,
  • if the check value is equal to 1, returns the true statement, else returns the false statement.

C Program To Find Whether A Number Is Prime Or Not Using Recursion:

#include <stdio.h>
 
int primenum(int, int);
 
int main()
{
    int num1, check;
    printf("Enter A Number To Find: ");
    scanf("%d", &num1);
    check = primenum(num1, num1 / 2);
    if (check == 1)
    {
        printf("%d is a prime number\n", num1);
    }
    else
    {
        printf("%d is not a prime number\n", num1);
    }
    return 0;
}
 
int primenum(int num1, int i)
{
    if (i == 1)
    {
        return 1;
    }
    else
    {
       if (num1 % i == 0)
       {
         return 0;
       }
       else
       {
         return primenum(num1, i - 1);
       }       
    }
}

Output:

Case 1: If the given number is not a prime number

not prime

Case 2: If the given number is a prime number

prime



About the author:
I like writing content about C/C++, DBMS, Java, Docker, general How-tos, Linux, PHP, Java, Go lang, Cloud, and Web development. I have 10 years of diverse experience in software development. Founder @ Studytonight