In: Computer Science
For a given integer n > 1, list all primes not exceeding n.
Example:
n=10, output: 2,3,5,7
n=16, output: 2,3,5,7,11,13
In Java please
For a given integer n > 1, list all primes not exceeding n.
Example:
n=10, output: 2,3,5,7
n=16, output: 2,3,5,7,11,13
In Java please.........
import java.util.Scanner; //importing scanner function
class PrimeNumber{ //class name
public static void main(String[] args){ // main method
Scanner s = new Scanner(System.in); //scanner declartion it is the
user input to read
System.out.println("enter the max number"); //printing the asking
user input range
int n = s.nextInt(); //reading user input
System.out.println("list of the prime number upto given range
"+n);
for(int i=2;i<=n;i++){ //for loop for range upto 2 to given
range . it will start 2
boolean isPrime = true; //boolean declartion
for (int j=2;j<=i/2;j++){ //inner loop
if(i%j == 0){ //logic for checking whether it prime or not
isPrime = false; //if is 0 its not prime
break;
}
}
if( isPrime == true) //if it not zero its prime
System.out.println(i); // printing the prime number
}
}
}
output:
enter the max number
16
list of the prime number upto given range 16
2
3
5
7
11
13
output1:
enter the max number
10
list of the prime number upto given range 10
2
3
5
7