aboutsummaryrefslogtreecommitdiff
path: root/challenge-169/adam-russell/java/ch-2.java
blob: 47c8d7813ec473de5e0f7ed595c597604f6a69c2 (plain)
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import java.util.ArrayList;

class Achilles{
    private static final double EPSILON = 1e-15;
    private static ArrayList primeFactors(long n){
        ArrayList factors = new ArrayList();    
        while (n % 2 == 0){
            factors.add(new Long(2));
            n = n / 2;
        }
        for(long i = 3; i <= Math.sqrt(n); i = i + 2){
            while (n % i == 0){
                factors.add(new Long(i));
                n = n / i;
            }
        }
        if(n > 2)
            factors.add(new Long(n));
        return factors;  
    }
    
    private static boolean isAchilles(int n){
        ArrayList factors = primeFactors(n);
        for(int i = 0; i < factors.size(); i++){
            if(n % Math.pow(((Long)factors.get(i)).longValue() + 0.0, 2) != 0)
                return false;
        }
        for(int i = 2; i <= Math.sqrt(n); i++) {
            double d = Math.log(n) / Math.log(i);
            if(Math.abs(d - Math.round(d)) < EPSILON)
                return false; 
        }
        return true;
    }
    
    public static ArrayList nAchilles(int n){
        ArrayList achilles = new ArrayList();
        int i = 1;
        do{
            i++;
            if(isAchilles(i))
                achilles.add(new Integer(i));
        }while(achilles.size() < n);
        return achilles;
    }

    public static void main(String[] args){        
        ArrayList achilles = Achilles.nAchilles(20);
        for(int i = 0; i < achilles.size() - 1; i++){
            System.out.print(achilles.get(i) + ", ");
        }
        System.out.println(achilles.get(achilles.size() - 1));
    }
}