|
| 1 | +/* |
| 2 | + * Copyright 2017 M. Isuru Tharanga Chrishantha Perera |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | +package com.github.chrishantha.sample.allocations; |
| 17 | + |
| 18 | +import com.beust.jcommander.JCommander; |
| 19 | +import com.beust.jcommander.Parameter; |
| 20 | + |
| 21 | +public class App { |
| 22 | + |
| 23 | + @Parameter(names = "--max", description = "Max Numbers") |
| 24 | + private long max = 10_000_000L; |
| 25 | + |
| 26 | + @Parameter(names = "--help", description = "Display Help", help = true) |
| 27 | + private boolean help; |
| 28 | + |
| 29 | + public static void main(String[] args) { |
| 30 | + App app = new App(); |
| 31 | + final JCommander jcmdr = new JCommander(app); |
| 32 | + jcmdr.setProgramName(App.class.getSimpleName()); |
| 33 | + jcmdr.parse(args); |
| 34 | + |
| 35 | + System.out.println(app); |
| 36 | + |
| 37 | + if (app.help) { |
| 38 | + jcmdr.usage(); |
| 39 | + return; |
| 40 | + } |
| 41 | + |
| 42 | + app.start(); |
| 43 | + } |
| 44 | + |
| 45 | + boolean isPrime(Long n) { |
| 46 | + //check if n is a multiple of 2 |
| 47 | + if (n % 2 == 0) return false; |
| 48 | + //if not, then just check the odds |
| 49 | + for (int i = 3; i * i <= n; i += 2) { |
| 50 | + if (n % i == 0) |
| 51 | + return false; |
| 52 | + } |
| 53 | + return true; |
| 54 | + } |
| 55 | + |
| 56 | + private void start() { |
| 57 | + Long primeCount = 0L; |
| 58 | + for (long i = 0; i < max; i++) { |
| 59 | + if (isPrime(i)) { |
| 60 | + primeCount++; |
| 61 | + } |
| 62 | + } |
| 63 | + System.out.format("Found %d prime numbers%n", primeCount); |
| 64 | + } |
| 65 | + |
| 66 | + @Override |
| 67 | + public String toString() { |
| 68 | + StringBuilder builder = new StringBuilder(); |
| 69 | + builder.append("App [max="); |
| 70 | + builder.append(max); |
| 71 | + builder.append("]"); |
| 72 | + return builder.toString(); |
| 73 | + } |
| 74 | +} |
0 commit comments