Blum integer: Difference between revisions
Content added Content deleted
(→{{header|Wren}}: Optimized - about 30% faster than before.) |
(→{{header|C}}: Updated in line with Wren example - run time now under 1 second.) |
||
Line 27: | Line 27: | ||
{{trans|Wren}} |
{{trans|Wren}} |
||
<syntaxhighlight lang="c">#include <stdio.h> |
<syntaxhighlight lang="c">#include <stdio.h> |
||
#include <stdbool.h> |
|||
#include <locale.h> |
#include <locale.h> |
||
int inc[8] = {4, 2, 4, 2, 4, 6, 2, 6}; |
int inc[8] = {4, 2, 4, 2, 4, 6, 2, 6}; |
||
bool isPrime(int n) { |
|||
// Assumes n is odd and bails out when factor count exceeds 2. |
|||
⚫ | |||
void primeFactors(int n, int *factors, int *length) { |
|||
if (n%2 == 0) return n == 2; |
|||
if (n == |
if (n%3 == 0) return n == 3; |
||
int d = 5; |
|||
while (d*d <= n) { |
|||
factors[count++] = 3; |
|||
if ( |
if (n%d == 0) return false; |
||
d += 2; |
|||
⚫ | |||
} |
|||
d += 4; |
|||
factors[count++] = 5; |
|||
⚫ | |||
n /= 5; |
|||
} |
} |
||
return true; |
|||
} |
|||
// Assumes n is odd. |
|||
int firstPrimeFactor(int n) { |
|||
if (n == 1) return 1; |
|||
if (!(n%3)) return 3; |
|||
if (!(n%5)) return 5; |
|||
for (int k = 7, i = 0; k*k <= n; ) { |
for (int k = 7, i = 0; k*k <= n; ) { |
||
if (!(n%k)) { |
if (!(n%k)) { |
||
return k; |
|||
⚫ | |||
⚫ | |||
} else { |
} else { |
||
k += inc[i]; |
k += inc[i]; |
||
Line 55: | Line 59: | ||
} |
} |
||
} |
} |
||
return n; |
|||
factors[count++] = n; |
|||
} |
|||
end: |
|||
*length = count; |
|||
} |
} |
||
int main() { |
int main() { |
||
int i = 1, j, bc = 0, |
int i = 1, j, bc = 0, p, q; |
||
int |
int blum[50], counts[4] = {0}, digits[4] = {1, 3, 5, 7}; |
||
setlocale(LC_NUMERIC, ""); |
setlocale(LC_NUMERIC, ""); |
||
while ( |
while (true) { |
||
p = firstPrimeFactor(i); |
|||
if ( |
if (p % 4 == 3) { |
||
q = i / p; |
|||
if (q != p && q % 4 == 3 && isPrime(q)) { |
|||
if (bc < 50) blum[bc] = i; |
|||
++counts[i % 10 / 3]; |
|||
++bc; |
|||
if (bc == 50) { |
|||
printf(" |
printf("First 50 Blum integers:\n"); |
||
for (j = 0; j < 50; ++j) { |
|||
printf("%3d ", blum[j]); |
|||
printf("\n"); |
if (!((j+1) % 10)) printf("\n"); |
||
} |
|||
printf("\n"); |
|||
if (bc == |
} else if (bc == 26828 || !(bc % 100000)) { |
||
printf(" |
printf("The %'7dth Blum integer is: %'9d\n", bc, i); |
||
if (bc == 400000) { |
|||
printf(" |
printf("\n%% distribution of the first 400,000 Blum integers:\n"); |
||
⚫ | |||
printf(" %6.3f%% end in %d\n", counts[j]/4000.0, digits[j]); |
|||
⚫ | |||
break; |
|||
} |
} |
||
⚫ | |||
} |
} |
||
} |
} |
||
} |
} |
||
i += (i % 5 == 3) ? 4 : 2; |
i += (i % 5 == 3) ? 4 : 2; |
||
} |
} |
||
return 0; |
return 0; |
||
}</syntaxhighlight> |
}</syntaxhighlight> |