Here we will see a simple program to check whether a number is prime or not using Recursion in C#.

What is Prime Number?

A prime number is a natural number greater than 1 that cannot be formed by multiplying two smaller natural numbers. A natural number greater than 1 that is not prime is called a composite number. For example, 5 is prime because the only ways of writing it as a product, 1 × 5 or 5 × 1, involve 5 itself.

C# Program to check whether a number is prime or not using Recursion:

Here is the source code to check whether a number is prime or not using Recursion.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CheckPrimeUsingRecursion
{
class Program
{
static void Main(string[] args)
{
int iNumber, iCheck;
Console.WriteLine("Enter a number: ");
iNumber = Convert.ToInt32(Console.ReadLine());
iCheck = CheckPrime(iNumber, iNumber / 2);
if (iCheck == 1)
{
Console.WriteLine("{0} is a prime number\n", iNumber);
}
else
{
Console.WriteLine("{0} is not a prime number\n", iNumber);
}
Console.ReadLine();
}
public static int CheckPrime(int num, int i)
{
if (i == 1)
{
return 1;
}
else
{
if (num % i == 0)
{
return 0;
}
else
{
return CheckPrime(num, i - 1);
}
}
}
}
}

Output:

>Enter a number:
>5
>5 is a prime number

View More:

Conclusion:

I hope this post will help you if you have just started writing the program. Please don’t hesitate for any technical help. Your feedback and suggestions are always valuable to me.

Thank You.

Leave a Comment