Showing posts with label check prime number. Show all posts
Showing posts with label check prime number. Show all posts

Write a program in java to check if a number is prime or not, by taking the number as input from the keyboard.

Write a program in java to check if a number is prime or not, by taking the number as input from the keyboard

Share:

Write a Java program to input a number and check if it is prime or not

 

Write a program  in Java to input a number and check if it is  prime or not

Prime Number : A number that is divisible only by itself and 1 (e.g. 2, 3, 5, 7, 11).

import java.util.Scanner;
public class Prime {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter A Positive Number : ");
int num=sc.nextInt();
sc.close();
boolean isPrime=true;
if (num==1) {
System.out.print(" 1 Is Unitary");
} else if(num==2) {
System.out.print(" 2 Is Prime Number");
}else {
for (int i = 2; i < num/2; i++) {
if (num%i==0) {
isPrime=false;
break;
}
}
if (isPrime) {
System.out.print(num +" Is Prime Number");
} else {
System.out.print(num +" Is Not Prime Number");
}
}
}
}

OUTPUT

1.
   Enter A Positive Number : 45
   45 Is Not Prime Number

2.
   Enter A Positive Number : 47
   47 Is Prime Number

Program 2

Share:

Write a program in c++ to input a number and check if it is prime or not

    

Write a program  in c++ to input a number and check if it is  prime or not

Prime Number : A number that is divisible only by itself and 1 (e.g. 2, 3, 5, 7, 11).

#include <iostream>
using namespace std;

int main()
{
    int numprime = 0;
    cout << "\t PROGRAM TO CHECK PRIME NUMBER";
    cout << "\n Enter A Number : ";
    cin >> num;
    if (num < 1)
        cout << "\n Number should be greater than 0";
    else if (num == 1)
        cout << "\n 1 is neither Prime nor Composite, It is a Neutral Number";
    else
    {

        for (int i = 2i <= num / 2; ++i)
        {
            if (num % i == 0)
            {
                prime = 1;
                cout << " It is not a Prime Number";
                break;
            }
        }

        if (prime == 0)
            cout << " It is a Prime Number";
        return 0;
    }
}


OUTPUT

1. 
        PROGRAM TO CHECK PRIME NUMBER
   Enter A Number : 45
   It is not a Prime Number

2. 
     PROGRAM TO CHECK PRIME NUMBER
   Enter A Number : 47
   It is a Prime Number


Share:

Pageviews