Files
  • Main.java
Main.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/*
 * Finds all the prime numbers up to N.
 *
 * To run this on repl.it, click on the "input" button at the top of the
 * right panel and specify N. Then click the "run" button above.
 */
public class Main {

  private static java.util.Scanner in = new java.util.Scanner(System.in);
  
  public static void main(String[] args) {
    int max = in.nextInt();
    int count = 0;
    for (int n = 2; n <= max; n++) {
      if (isPrime(n)) {
        System.out.printf("%d, ", n);
        count++;
      }
    }
    System.out.printf("%nFound %d primes up to %d%n", count, max);
  }
  
  private static boolean isPrime(int n) {
    if (n < 2) 
      return false;
      
    for (int i = 2, limit = (int) Math.sqrt(n); i <= limit; i++) {
      if (n % i == 0) {
        return false;
      }
    }
    
    return true;
  }
  
}