Advertisement
Guest User

Untitled

a guest
Jul 23rd, 2017
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.10 KB | None | 0 0
  1. package org.shaunren.misc;
  2. import java.util.*;
  3.  
  4. public class PrimeNumberFinder {
  5.     public static void main(String[] args) {
  6.         Scanner sc = new Scanner(System.in); // this is an object that reads stuff from console
  7.        
  8.         System.out.print("How many numbers do you want today? [1-10000]: ");
  9.         int count = sc.nextInt(); // gets the input from the user
  10.        
  11.         if (count < 1 || count > 10000) {
  12.             System.out.println("Invalid input.");
  13.             return;
  14.         }
  15.         int[] primes = new int[count]; // this is the array that contains all the primes
  16.        
  17.         primes[0] = 2;
  18.        
  19.         int curNum = 3;
  20.         for (int i=1; i<count; i++) {
  21.             boolean foundPrime = false;
  22.            
  23.             while (!foundPrime) {
  24.                 boolean primeNumber = true;
  25.                 for (int j=0; j<count; j++) {
  26.                     if (primes[j] == 0) break;
  27.                     if (curNum % primes[j] == 0) {
  28.                         primeNumber = false;
  29.                         break;
  30.                     }
  31.                 }
  32.            
  33.                 if (primeNumber) { // put it into the array
  34.                     primes[i] = curNum;
  35.                     foundPrime = true;
  36.                 }
  37.            
  38.                 curNum += 2;
  39.             }
  40.         }
  41.        
  42.         // print the array
  43.         System.out.println("Prime numbers: ");
  44.         for (int i=0; i<count; i++) {
  45.             System.out.println(primes[i]);
  46.         }
  47.        
  48.     }
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement