Guest User

First 'X' Prime Numbers

a guest
Oct 29th, 2018
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.28 KB | None | 0 0
  1. /**
  2.  * This program displays the first X prime numbers. X being the number of terms entered by the user.
  3.  */
  4. import java.util.Scanner;
  5. public class First_Primes
  6. {
  7.     static boolean isPrime(int num) //Function to check whether a number is prime or not.
  8.     {
  9.         if(num == 2)
  10.             return true;
  11.         else
  12.         {
  13.             int i, flag = 1;
  14.             for(i=2;i<num;i++)
  15.             {
  16.                 if(num % i == 0)
  17.                 {
  18.                     flag = 0;
  19.                     break;
  20.                 }
  21.             }
  22.             if(flag == 1)
  23.                 return true;
  24.             else
  25.                 return false;
  26.         }
  27.     }
  28.    
  29.     static void display(int[] a) //Function to display the array of prime numbers.
  30.     {
  31.         int i;
  32.         for(i=0;i<a.length-1;i++)
  33.         {
  34.             System.out.print(a[i] + " | ");
  35.         }
  36.         System.out.println(a[a.length-1]+".");
  37.     }
  38.    
  39.     public static void main(String[] args)
  40.     {
  41.         Scanner sc = new Scanner(System.in);
  42.         System.out.println("Please enter the number of terms.");
  43.         int terms = sc.nextInt();
  44.         int[] primes = new int[terms];
  45.         int i= 2, ct = 0;
  46.        
  47.         while(i>0) //Creating an "infinite" loop.
  48.         {
  49.             if(isPrime(i))
  50.             {
  51.                 primes[ct] = i;
  52.                 ct++;
  53.                 if(ct == terms) //Breaking/ending the "infinite" loop when the number of terms required are stored.
  54.                     break;
  55.             }
  56.             i++;
  57.         }
  58.         System.out.println("The first "+terms+" primes numbers are:");
  59.         display(primes);
  60.         sc.close();
  61.     }
  62. }
Add Comment
Please, Sign In to add comment