Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * This program displays the first X prime numbers. X being the number of terms entered by the user.
- */
- import java.util.Scanner;
- public class First_Primes
- {
- static boolean isPrime(int num) //Function to check whether a number is prime or not.
- {
- if(num == 2)
- return true;
- else
- {
- int i, flag = 1;
- for(i=2;i<num;i++)
- {
- if(num % i == 0)
- {
- flag = 0;
- break;
- }
- }
- if(flag == 1)
- return true;
- else
- return false;
- }
- }
- static void display(int[] a) //Function to display the array of prime numbers.
- {
- int i;
- for(i=0;i<a.length-1;i++)
- {
- System.out.print(a[i] + " | ");
- }
- System.out.println(a[a.length-1]+".");
- }
- public static void main(String[] args)
- {
- Scanner sc = new Scanner(System.in);
- System.out.println("Please enter the number of terms.");
- int terms = sc.nextInt();
- int[] primes = new int[terms];
- int i= 2, ct = 0;
- while(i>0) //Creating an "infinite" loop.
- {
- if(isPrime(i))
- {
- primes[ct] = i;
- ct++;
- if(ct == terms) //Breaking/ending the "infinite" loop when the number of terms required are stored.
- break;
- }
- i++;
- }
- System.out.println("The first "+terms+" primes numbers are:");
- display(primes);
- sc.close();
- }
- }
Add Comment
Please, Sign In to add comment