Prime number program in Java

Algorithm

Prime numbers are those which are not divisible by any other number apart from 1 and the number itself. Zero (0), one (1) and negative numbers (e.g., -2, -3, -5) are not prime numbers.

Java Code

package com.physicsinfo;

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        int n, flag=0;
        System.out.print("Enter a whole number(integer): ");
        Scanner sc = new Scanner(System.in);
        n = sc.nextInt();
        if (n==0 || n==1|| n<0) {// 0,1 and negative numbers are not prime numbers
            flag=1;
        }
        if (n!=0 && n!=1) {
            for (int i = 2; i <= n / 2; i++) {
                if (n % i == 0) {       //prime numbers aren't divisible by any other number apart from 1 and the number itself
                    flag = 1;
                }
            }
        }
        if(flag==0){
            System.out.println(n +" is a prime number.");}
        else {
            System.out.println(n +" is not a prime number.");
        }
        }

    }

Leave a Comment

Your email address will not be published.