In: Computer Science
Write a C function boolean isPrime (int n), that would take a positive integer n as a parameter and return true or false whether the number is a prime number. You should check the range of n and print proper message (For example, if n is a genitive number, you should print out an error message).
#include <stdio.h>
#define bool int
#define true 1
#define false 0
bool isPrime(int number)
{
int flag = true;
for(int i=2;i<=number/2;i++)
{
if(number%i == 0) // divisible by any number between 2 to number
-1
flag = false;
}
return flag;
}
int main(void) {
int num;
printf("Enter the number to be checked if its prime :
");
scanf("%d",&num);
if(num < 0)
printf("\nError : The entered number is negative
");
if(num == 1 || num ==2 || num ==3)
printf("Error : ");
else if(isPrime(num) == true)
printf("\nNumber %d is prime",num);
else
printf("\nNumber %d is not prime",num);
return 0;
}
Output:
Enter the number to be checked if its prime : Number 13 is prime
Do ask if any doubt. Please upvote.