Jump to content

Self numbers: Difference between revisions

→‎{{header|C}}: Added 'extended' version.
(→‎{{header|C}}: Removed unnecessary variable declarations.)
(→‎{{header|C}}: Added 'extended' version.)
Line 14:
 
=={{header|C}}==
===Sieve based===
{{trans|Go}}
The 'sieve based' version.
 
About 25% faster than Go (using GCC 7.5.0 -O3) mainly due to being able to iterate through the sieve using a pointer.
<lang c>#include <stdio.h>
Line 89 ⟶ 88:
The 100 millionth self number is 1022727208
Took 1.521486 seconds.
</pre>
 
===Extended===
{{trans|Pascal}}
<lang c>#include <stdio.h>
#include <stdlib.h>
#include <time.h>
 
typedef unsigned char bool;
 
#define TRUE 1
#define FALSE 0
#define MILLION 1000000LL
#define BILLION 1000 * MILLION
#define MAX_COUNT 103LL*10000*10000 + 11*9 + 1
 
int digitSum[10000];
 
void init() {
int i = 9999, s, t, a, b, c, d;
for (a = 9; a >= 0; --a) {
for (b = 9; b >= 0; --b) {
s = a + b;
for (c = 9; c >= 0; --c) {
t = s + c;
for (d = 9; d >= 0; --d) {
digitSum[i] = t + d;
--i;
}
}
}
}
}
 
void sieve(bool *sv) {
int a, b, c;
long long s, n = 0;
for (a = 0; a < 103; ++a) {
for (b = 0; b < 10000; ++b) {
s = digitSum[a] + digitSum[b] + n;
for (c = 0; c < 10000; ++c) {
sv[digitSum[c]+s] = TRUE;
++s;
}
n += 10000;
}
}
}
 
int main() {
long long count = 0, limit = 1;
clock_t begin = clock(), end;
bool *p, *sv = (bool*) calloc(MAX_COUNT, sizeof(bool));
init();
sieve(sv);
printf("Sieving took %lf seconds.\n", (double)(clock() - begin) / CLOCKS_PER_SEC);
printf("\nThe first 50 self numbers are:\n");
for (p = sv; p < sv + MAX_COUNT; ++p) {
if (!*p) {
if (++count <= 50) {
printf("%ld ", p-sv);
} else {
printf("\n\n Index Self number\n");
break;
}
}
}
count = 0;
for (p = sv; p < sv + MAX_COUNT; ++p) {
if (!*p) {
if (++count == limit) {
printf("%10lld %11ld\n", count, p-sv);
limit *= 10;
if (limit == 10 * BILLION) break;
}
}
}
printf("\nOverall took %lf seconds.\n", (double)(clock() - begin) / CLOCKS_PER_SEC);
return 0;
}</lang>
 
{{out}}
<pre>
Sieving took 7.429969 seconds.
 
The first 50 self numbers are:
1 3 5 7 9 20 31 42 53 64 75 86 97 108 110 121 132 143 154 165 176 187 198 209 211 222 233 244 255 266 277 288 299 310 312 323 334 345 356 367 378 389 400 411 413 424 435 446 457 468
 
Index Self number
1 1
10 64
100 973
1000 10188
10000 102225
100000 1022675
1000000 10227221
10000000 102272662
100000000 1022727208
1000000000 10227272649
 
Overall took 11.574158 seconds.
</pre>
 
9,490

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.