Home Java Javatutorial Prime Number program in Java
Questions:Ask|Latest


 
 

Share on Google+Share on Google+

Prime Number program in Java

Advertisement
Prime Number program in Java will print the prime numbers between 1 to any given number. Prime Number is a number that is not divisible by any number other than 1 or itself. Similar logic is used in program will displaying the result. The following is a simple program, which automatically prints prime number starting from 1 to 50.

Prime Number program in Java will print the prime numbers between 1 to any given number.

Prime Number is a number that is not divisible by any number other than 1 or itself. Similar logic is used in program will displaying the result.

At first PrimeNumber class is defined. We create a main() method. Here in the example we have taken 50 as the value of int, programmers can use any value here. Then for loop is created.

The following is a simple program, which automatically prints Prime Number starting from 1 to 50.

Example of Prime Number program in Java:
package Tutorial;

public class PrimeNumber {
	public static void main(String[] args) {
		int num = 50;
		System.out.println("prime number from 1 to " + num );
		for (int i = 1; i < 50; i++) {

			boolean b = true;

			for (int j = 2; j < i; j++) {

				if (i % j == 0) {
					b = false;
					break;
				}
			}

			if (b)
				System.out.print(i + " ");
		}
	}
}

Output:

Prime Number from 1 to 50

1 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47

Advertisements

Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: May 2, 2013

Ask Questions?    Discuss: Prime Number program in Java  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
DMCA.com