Prime Numbers up to N
Write a Program
to Display all Prime Numbers up to N ?
package Programs;
import
java.util.Scanner;
public class
PrimeNumbersUpToN
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a
number (n): ");
int n = scanner.nextInt();
System.out.println("Prime
numbers up to " + n + ":");
for (int i = 2; i <= n; i++)
{
if (isPrime(i))
{
System.out.print(i + ", ");
}
}
}
public static boolean isPrime(int num)
{
if (num <= 1)
{
return false;
}
// Check from 2 to the square root of
the number if there are any divisors.
for (int i = 2; i * i <= num; i++)
{
if (num % i == 0)
{
return false;
}
}
return true;
}
}
Enter a number (n): 101
Prime numbers up to 101:
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101
2.In the isPrime function, we first check if the number is less than or equal to 1. Numbers less than or equal to 1 are not considered prime, so we return false.
3.Then, we use a for loop to check for divisors of the number from 2 up to the square root of the number. Checking divisors only up to the square root is sufficient because any factor larger than the square root must have a corresponding factor smaller than the square root.
4.If we find any divisor within the loop, the number is not prime, and we return false.
5.If no divisors are found, the number is prime, and we return true.
6.In the main function, we ask the user to input a positive integer 'N' using the Scanner class.
7.We then iterate from 2 to 'N' and check if each number is prime using the isPrime function. If it is prime, we print it to the console.
Comments
Post a Comment