493f84c275d3a2ef6f9e38dfd053be5d5e9dd832
[sdk] / samples / eC / FindPrime / findPrime.ec
1 public class FindPrime
2 {
3    Array<int> primeList { [ 2 ], minAllocSize = 64 };
4    int index;
5
6    index = 3;
7
8    bool HasPrimeFactor(int x)
9    {
10       int max = (int)floor(sqrt((double)x));
11      
12       for(i : primeList)
13       {
14          if(i > max) break;
15          if(x % i == 0) return true;
16       }
17       return false;
18    }
19
20    public int GetPrime(int x)
21    {
22       if(x > primeList.count - 1)
23       {
24          for (; primeList.count != x; index += 2)
25             if(!HasPrimeFactor(index))
26             {
27                if(primeList.count >= primeList.minAllocSize) primeList.minAllocSize *= 2;
28                primeList.Add(index);
29             }
30       }
31       return primeList[x-1];
32    }
33 }
34
35 class PrimeApp : Application
36 {
37    FindPrime fp { };
38    void Main()
39    {
40       int num = argc > 1 ? atoi(argv[1]) : 1;
41       PrintLn(fp.GetPrime(num));
42    }
43 }