Description
A number is called prime if it is divisible by 1 and number itself. To check the number is prime, check the number is divisible any number from 2 to half of the number.
C/C++
/* C Program to Check Whether a Number is Prime or Not */ //Save it as CheckPrime.c #include<stdio.h> int main(){ int i, number, flag=0; printf("Enter a number : "); scanf("%d",&number); //Traverse from 2 to half of the number for(i=2;i<=(number/2);i++){ /*If number is divisible by any of the number then it is composite and come out of the loop*/ if(number%i == 0){ flag=1; break; } } if(number==1){ printf("The number is neither prime nor composite"); } else{ if(flag==1){ printf("The number is not a prime number"); } else{ printf("The number is a prime number"); } } return 0; }
Input: Enter a number : 7 Output: The number is a prime number
Java
/* Java Program to Check Whether a Number is Prime or Not */ //Save it as CheckPrime.java import java.io.*; import java.util.Scanner; public class CheckPrime { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int i, number, flag=0; System.out.println("Enter a number : "); number = scanner.nextInt(); //Traverse from 2 to half of the number for(i=2;i<=(number/2);i++){ /*If number is divisible by any of the number then it is composite and come out of the loop*/ if(number%i == 0){ flag=1; break; } } if(number==1){ System.out.print("The number is neither prime nor composite"); } else{ if(flag==1){ System.out.print("The number is not a prime number"); } else{ System.out.print("The number is prime number"); } } } }
Input: Enter a number : 4 Output: The number is not a prime number
Related Programs
1) Program to Check Whether a Number is Even or Odd2) Program to Check Whether a Character is a Vowel or Not
3) Program To Check Armstrong Number
4) Check whether a given number is a perfect number or not
5) Program to Check Leap Year
6) Program to calculate Volume and Surface Area of Sphere
7) Program to add two complex numbers
8) Program to find HCF using Recursion
9) Program to calculate square root of a number without using standard library function sqrt()
10) Program to find HCF(Highest Common Factor)/GCD(Greatest Common Divisor) and LCM(Least Common Multiple)