Here, we have a basic program example to check if the number is prime or not with functions using different languages. This program is created in c language, c++, Java, and Python.
Function to check if the number is prime in C language
#include<stdio.h>
int PrimeOrNot(int);
int main()
{
int n1,prime;
printf(" Enter a positive number : ");
scanf("%d",&n1);
prime = PrimeOrNot(n1);
if(prime==1)
printf(" The number %d is a prime number.\n",n1);
else
printf(" The number %d is not a prime number.\n",n1);
return 0;
}
int PrimeOrNot(int n1)
{
int i=2;
while(i<=n1/2)
{
if(n1%i==0)
return 0;
else
i++;
}
return 1;
}
Function to check if the number is prime in C++ language
#include <iostream>
using namespace std;
bool isPrime(int num);
int main(){
int num;
bool flag;
cout<<"Enter any positive number: ";
cin>>num;
flag = isPrime(num);
if (flag==true)
cout<<num<<" is a prime number";
else
cout<<num<<" is not a prime number";
return 0;
}
bool isPrime(int num){
bool flag=true;
for(int i = 2; i <= num / 2; i++) {
if(num % i == 0) {
flag = false;
break;
}
}
return flag;
}
Function to check if the number is prime in Python language
num = int(input("Enter a positive integer: "))
def checkPrime(num):
if(num <= 1):
return False
for i in range(2,num):
if(num % i)==0:
return False
return True
if(checkPrime(num)):
print(num," is a Prime number.")
else:
print(num," is not a prime number.")