Prime Checker

  • + 1 comment

    I never use import static before, this problem gives me good insight. Also, searching for math equation for checkPrime and adapt it to java is fun, and it remind me that (int / int( will automatically truncate decimal point !!

    here is my solution:

    import static java.lang.System.in;
    
    class Factorial {
        public static int calFactorial(int in) {
            int cal = 1;
            
            while (in > 0) {
                cal = cal * in;
                in--;
            }
            
            return cal;
        }
    }
    
    class Prime {
        public void checkPrime(int ...args) {
            String res = "";
            
            for (int i : args) {
                if (i != 0 && i != 1) {    
                    // this is Willans' formula            
                    double result = Math.pow(Math.cos(Math.PI * ((Factorial.calFactorial(i - 1) + 1) / (double) i)), 2);
                    
                    if (result >= 1) {
                        if (res.length() > 0) {
                            res = res + " " + i;
                        } else {
                            res = res + i;
                        }
                    }
                }
            }
            
            if (res.isEmpty()) {
                System.out.println("");
            } else {
                System.out.println(res);
            }
        }
    }