Home » Java solved programs » Core java programs

Java program to check whether a given number is prime or composite (non-prime)

In this java program, we are going to check whether a given number is primer or composite (non-prime).
Submitted by Preeti Jain, on March 11, 2018

Given an integer number and we have to check whether it is prime or composite (non-prime) using java?

Check prime or composite (non-prime) in java

import java.util.Scanner;

class CheckNumberPrimeOrCompositeClass{
	public static void main(String[] args){
		//create Scanner class object for user input
		Scanner sc = new Scanner(System.in);

		// Display message for user understanding
		System.out.println("Enter any number");

		//Accept input from keyboard
		int input_num = sc.nextInt();
		// i variable initialize by 2 just 
		// because every number is divisible by 1
		int i=2;
		//Loop continues till input_num to 0
		while(input_num>0){
			// Entered number will be checked by i if we get 0 
			// then number is not prime then will check from next increment i
			if(input_num%i==0)
				break;
			i++;
		}

		if(input_num == i)
			System.out.println("Number is prime");
		else
			System.out.println("Number is not prime");
	}
}

Output

Run(1)
D:\Java Articles>java CheckNumberPrimeOrCompositeClass
Enter any number
7
Number is prime

Run(2)
D:\Java Articles>java CheckNumberPrimeOrCompositeClass
Enter any number
10
Number is not prime






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.