Program to check whether a number is Prime or not
Prerequisite:-
Understand the concept of prime numbers:- A prime number is only divisible by 1 and itself.
Cpp Code to check Prime Number
#include <iostream>
using namespace std;
int main()
{
int c,num,flag=0;
c=2;
cin>>num;
if(num<2){cout<<"Prime";}
while(num/2>=c){
if(num%c==0){flag=1;break;}
c++;
}
if(!flag){cout<<"Prime";}
else {cout<<"Not Prime";}
return 0;
}
Input: 3
Output: Prime
Input: 29
Output: Prime
Input: 50
Output: Not Prime
Prime Number Code in Python
num = int(input())
flag = 0
c = 2
if num < 2:
print("Prime")
while num / 2 >= c:
if num % c == 0:
flag = 1
break
c += 1
if not flag:
print("Prime")
else:
print("Not Prime")
Input: 3
Output: Prime
Input: 29
Output: Prime
Input: 50
Output: Not Prime
Java code for Prime Number
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int num, flag = 0;
int c = 2;
Scanner scanner = new Scanner(System.in);
num = scanner.nextInt();
if (num < 2) {
System.out.println("Prime");
}
while (num / 2 >= c) {
if (num % c == 0) {
flag = 1;
break;
}
c++;
}
if (flag == 0) {
System.out.println("Prime");
} else {
System.out.println("Not Prime");
}
}
}
Input: 3
Output: Prime
Input: 29
Output: Prime
Input: 50
Output: Not Prime
Comments
Post a Comment