Checking If a Number is Prime then Printing all preceding primes in Java

Problem:

The problem is divided into two parts. First, you should write a program that reads an integer N from the user and checks if the input is a prime number using static boolean isPrime(int N) that returns true if N is a prime and false otherwise. Then, you should extend the program to determine all prime numbers between 2 and N and store them in an array. You can create an array of size N since the number of primes between 2 and N is bounded above by N. Finally, all found prime numbers should be displayed.


Output:

Enter a number:
53
53 is a prime
The list of primes: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53


Solution:

import java.util.Scanner;
  
public class Problem3
{
  public static boolean isPrime (int N)
  {
  boolean prime = true; 
  for ( int i = 2; i < N; i++ )
  {
   if ( N % i == 0 )
   {
    prime = false;
   }
  }
   
  return prime;
  
  }
  
  public static void main (String[] args)
  {
   int j =0;
   Scanner scan = new Scanner (System.in);
   System.out.println("Enter a number:");
   int N = scan.nextInt();
   int[] list = new int[N];
   if (isPrime(N))
    System.out.print(N+ " is a prime");
   else System.out.print(N+ " is not a prime.");
    for ( int i = 2; i <= N; i++ )
    {
      if ( isPrime(i) )
      {
       list[j] = i;
       j++;
      }
    }
    System.out.println();
    System.out.print("The list of primes: ");
   for (int values: list)
   {
    if (values != 0)
    System.out.print(values + " ");
   }
      
   
  }
}

No comments:

Post a Comment