DEV Community 👩‍💻👨‍💻

Sulaiman Aminu Barkindo
Sulaiman Aminu Barkindo

Posted on

C Program for Prime Number Using Recursion

Introduction
Prime number is a number that is greater than 1 and can be divided only by 1 or itself. In other words, prime numbers can't be divided by numbers other than itself or 1. Example of prime numbers are 2, 3, 5, 7, 11, ...

Implementation
I made the implementation in two functions to aid readability.

/**
 * is_prime - detects if an input number is a prime number.
 * @n: input number.
 * @i: iterator.
 * Return: 1 if n is a prime number. 0 if n is not a prime number.
 */
int is_prime(unsigned int n, unsigned int i)
{
        if (n % i == 0)
        {
                if (n == i)
                        return (1);
                else
                        return (0);
        }
        return (0 + is_prime(n, i + 1));
}
/**
 * is_prime_number - detects if an input number is a prime number.
 * @n: input number.
 * Return: 1 if n is a prime number. 0 if n is not a prime number.
 */
int is_prime_number(int n)
{
        if (n <= 1)
                return (0);
        return (is_prime(n, 2));
}
Enter fullscreen mode Exit fullscreen mode
is_prime_number
Enter fullscreen mode Exit fullscreen mode

make the first check that the number supplied is not 1 or less than 1 as prime numbers only start from 2 upward. Then call

is_prime
Enter fullscreen mode Exit fullscreen mode

to finish the check if the function is a prime number.

Final Thoughts
This is my implementation of C program to check prime number, feel free to give your thoughts in the comment section.

Top comments (0)

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.