write a function to check whether a number is prime
Answers
Python program to check whether a number is Prime or not
Given a positive integer N, The task is to write a Python program to check if the number is prime or not.
Definition: A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. The first few prime numbers are {2, 3, 5, 7, 11, ….}.
Examples :
Input: n = 11
Output: true
Input: n = 15
Output: false
Input: n = 1
Output: false
The idea to solve this problem is to iterate through all the numbers starting from 2 to (N/2) using a for loop and for every number check if it divides N. If we find any number that divides, we return false. If we did not find any number between 2 and N/2 which divides N then it means that N is prime and we will return True.
Below is the Python program to check if a number is prime:
// C program for
// the above approach
#include <stdio.h>
int main()
{
// Given number
int n = 11;
// checking the given number
// whether it is 1 or not
if (n == 1) {
printf("%d is not a prime number", n);
}
else {
int f = 0;
// iterate from 2 to n/2
for (int i = 2; i <= (n / 2); i++) {
// If n is divisible by any number between
// 2 and n/2, it is not prime
if (n % 2 == 0) {
f = 1;
// break out of for loop as
// it is not prime
break;
}
}