Primality by trial division: Difference between revisions
Content deleted Content added
Updated all D entries |
|||
Line 564: | Line 564: | ||
<lang d>import std.stdio, std.algorithm, std.range, std.math; |
<lang d>import std.stdio, std.algorithm, std.range, std.math; |
||
bool |
bool isPrime1(in int n) pure nothrow { |
||
if |
if (n == 2) |
||
return |
return true; |
||
⚫ | |||
⚫ | |||
for(int i = 3; i <= |
for(int i = 3; i <= real(n).sqrt; i += 2) |
||
if (n % i == 0) |
if (n % i == 0) |
||
return false; |
return false; |
||
Line 574: | Line 576: | ||
} |
} |
||
void main() { |
void main() { |
||
iota(2, 40).filter! |
iota(2, 40).filter!isPrime1.writeln; |
||
}</lang> |
}</lang> |
||
{{out}} |
{{out}} |
||
Line 582: | Line 584: | ||
===Version with excluded multiplies of 2 and 3=== |
===Version with excluded multiplies of 2 and 3=== |
||
Same output. |
Same output. |
||
⚫ | |||
⚫ | |||
⚫ | |||
// Test 1, 2, 3 and multiples of 2 and 3: |
|||
⚫ | |||
⚫ | |||
else if (n < 2 || n % 2 == 0 || n % 3 == 0) |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
// |
// incrementing by 2 and 4 alternatively, that is: |
||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
for (It div = 5, inc = 2; div ^^ 2 <= n; div += inc, inc = 6 - inc) |
|||
if (n % div == 0) |
|||
⚫ | |||
return false; |
|||
return true; |
|||
⚫ | |||
⚫ | |||
* by starting at 5 and incrementing by 2 and 4 |
|||
* alternatively, that is: |
|||
⚫ | |||
⚫ | |||
for (Integer divisor = 5, increment = 2; divisor*divisor <= number; |
|||
divisor += increment, increment = 6 - increment) |
|||
⚫ | |||
⚫ | |||
return true; // if we get here, the number is prime |
|||
} |
} |
||
void main() { |
void main() { |
||
⚫ | |||
⚫ | |||
⚫ | |||
}</lang> |
}</lang> |
||
===Two Way Test=== |
===Two Way Test=== |
||
Odd divisors is generated both from increasing and decreasing sequence, may improve performance for numbers that have large minimum factor. |
Odd divisors is generated both from increasing and decreasing sequence, may improve performance for numbers that have large minimum factor. |
||
Line 617: | Line 618: | ||
if (n % 2 == 0 || n <= 1) |
if (n % 2 == 0 || n <= 1) |
||
return n == 2; |
return n == 2; |
||
T head = 3, tail = (cast(T) |
T head = 3, tail = (cast(T)real(n).sqrt / 2) * 2 + 1; |
||
for ( ; head <= tail ; head +=2, tail -= 2) |
for ( ; head <= tail ; head +=2, tail -= 2) |
||
if ((n % head) == 0 || (n % tail) == 0) |
if ((n % head) == 0 || (n % tail) == 0) |
||
Line 624: | Line 625: | ||
} |
} |
||
void main() { |
void main() { |
||
iota(2, 40).filter!isPrime3 |
iota(2, 40).filter!isPrime3.writeln; |
||
}</lang> |
}</lang> |
||