Created
August 25, 2019 09:36
-
-
Save trpfrog/b59b98852286c618d8336760286ea3de to your computer and use it in GitHub Desktop.
素数判定プログラムです。(4年前より速い)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import java.util.ArrayList; | |
| import java.util.List; | |
| public class PrimeSearch { | |
| public static List<Integer> primeList; | |
| public static int maxSearchIdx = 0; | |
| public static void main(String[] args){ | |
| int number = 2019; | |
| int numberOfPrime = 6*number/(int)(Math.round(Math.log(number)*5)); | |
| // 素数定理よりn/logn を余裕を持して1.2倍した | |
| primeList = new ArrayList<>(numberOfPrime); | |
| primeList.add(2); | |
| for(int i = 3; i <= number; i++){ | |
| addToPrimeList(i); | |
| } | |
| System.out.println(number+"は素数"+(primeList.contains(number)?"です":"ではありません")); | |
| } | |
| public static boolean addToPrimeList(int n){ | |
| while(Math.sqrt(n) >= primeList.get(maxSearchIdx)){ | |
| maxSearchIdx++; | |
| } | |
| for(int i=0; i<=maxSearchIdx; i++){ | |
| if(n % primeList.get(i) == 0) | |
| return false; | |
| } | |
| primeList.add(n); | |
| return true; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment