When testing whether an integer is a prime, it is sufficient to try to divide by integers up to and including the square root of the number being tested.
Output of Above Java Program
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
public class Primes { public static void main(String args[]) { int maxValue = 50; // The maximum value to be checked. // Check all values from 2 to maxValue: OuterLoop: for(int i = 2 ; i <= maxValue ; ++i) { // Try dividing by all integers from 2 to square root of i: for(int j = 2 ; j <= Math.sqrt(i) ; ++j) { if(i%j == 0) // This is true if j divides exactly continue OuterLoop; // so exit the loop. } // We only get here if we have a prime: System.out.println(i); // so output the value. } } }
Output of Above Java Program
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
import java.util.*;
class Prime
{
public static void main(String str[])
{
Scanner in=new Scanner(System.in);
System.out.println("Enter number upto which u want to find prime numbers: ");
int n=in.nextInt();
System.out.println("The prime numbers are:");
for(int i=2;i<=n;i++)
{
int k=0;
for(int j=2;j<=i;j++)
{
if(i%j==0){
k=k+1;
}
}
if(k==1){
System.out.println(i);
}
}
}
}