Java program to print the prime numbers

Friday, October 2nd, 2009

Write a Java program that prompts the user for an integer and then prints out all prime numbers up to that integer.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.util.Scanner;
class prime
{
	public static void main(String[] args)
	{
		int n,p;
		Scanner s=new Scanner(System.in);
		System.out.println(“Enter upto which number prime numbers are needed”);
		n=s.nextInt();
		for(int i=2;i<n;i++)
		{
			p=0;
			for(int j=2;j<i;j++)
			{
				if(i%j==0)
				p=1;
			}
			if(p==0)
				System.out.println(i);
		}
	}
}

Output:

Enter upto which number prime numbers are needed:20
2
3
5
7
11
13
17
19

Enter up to which number prime numbers are needed:35

2
3
5
7
11
13
17
19
23
29
31

Avatar Image

Author Name :
Ranjith

Total : 2 Comments


2 Responses to “Java program to print the prime numbers”

  1. mallo says:

    its not worling n blue j

  2. Rajib Ghosh says:

    import java.util.Scanner;
    class prime
    {
    public static void main(String[] args)
    {
    int n,p;
    Scanner s=new Scanner(System.in);
    System.out.println(“Enter upto which number prime numbers are needed”);
    n=s.nextInt();
    for(int i=2;i<n;i++)
    {
    p=0;
    for(int j=2;j<i;j++)
    {
    if(i%j==0)
    p=1;
    }
    if(p==0)
    System.out.println(i);
    }
    }
    }

Leave a Reply

Question and Answer
C/C++ Unix & Linux Wordpress
Source codes
C C++ Java

Free email signup