Home Tutorial Java Core Java find prime numbers without using break statement

 
 

Java find prime numbers without using break statement
Posted on: September 22, 2012 at 12:00 AM
In this tutorial, you will learn how to find the prime numbers without using break statement.

Java find prime numbers without using break statement

In this tutorial, you will learn how to find the prime numbers without using break statement.

You all are aware of Prime Numbers, these are the numbers which are either divided by 1or by themselves. There are different ways of finding the prime numbers. In many of the programs, break statement is used to quit the loop. Actually this break statement transfer the control at the end of the loop. This tutorial is quite different in finding the prime numbers.Here, break statement is not used.

Example:

import java.io.*;
class FindPrimeWithoutBreak
{
public static void main(String[] args) {
System.out.println("Prime Numbers between 2 and 50: ");
for (int number = 2; number <= 50; number++) {
int maxFactor = (int)Math.sqrt(number);
boolean isPrime = true;
int factor = 2;
while (isPrime && factor <= maxFactor) {
if (number % factor == 0) { 
isPrime = false;
}
factor++;
}
if (isPrime) System.out.println(number);
}
}
}

Output:

Prime Numbers between 1 and 50:
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47

Related Tags for Java find prime numbers without using break statement:


Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.