Checking if an int is prime more efficiently

前端 未结 11 795
暗喜
暗喜 2020-12-11 04:20

I recently was part of a small java programming competition at my school. My partner and I have just finished our first pure oop class and most of the questions were out of

11条回答
  •  甜味超标
    2020-12-11 04:45

    Another speed improvement you can make in main is to change your loop to pre-filter some composite numbers, unrolling some iterations into a sequence of tests. The simplest is to test 2 outside the loop, then test odd numbers (2*i+1). Slightly more complex is to test 2, 3, then 6*i ± 1. You can keep extending this approach, testing the first n primes, then looping oven pn# * i+j, where pn# is the prime primordial (the product of the first n primes) and j is a positive integer less than and coprime to pn#.

    To speed up the prime method, you could start with a fast probabilistic prime test and test using a slower deterministic test only for those cases the probabilistic test can't determine.

提交回复
热议问题