Prime number
A prime number is an integer greater than 1 whose only factors are 1 and itself. A factor is an integer that can be divided evenly into another number.
Logic
To print all the prime numbers up to N, we start one loop from 2 to N and then inside the loop we check current number or “num” is prime or not. To check if it is prime or not we again need one nested loop. It is not an efficient way to check prime number but it is simpler to understand the basic of looping in Java.
See also: Check whether a number is prime number or not
Program
import java.util.Scanner; public class PrimeNumbersUptoN { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Take input from user System.out.print("Find prime numbers upto : "); int upto = scanner.nextInt(); System.out.println("\nAll prime numbers upto " + upto + " are : "); for(int num = 2; num <= upto; num++) { int i; for(i = 2; i <= (num / 2); i++) { if(num % i == 0) { i = num; break; } } // If the number is prime then print it. if(i != num) { System.out.print(num + " "); } } } }
Output
Find prime numbers upto : 100
All prime numbers upto 100 are :
3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97