Skip to content

Instantly share code, notes, and snippets.

@wellle
Last active December 20, 2015 00:59
Show Gist options
  • Save wellle/6045466 to your computer and use it in GitHub Desktop.
Save wellle/6045466 to your computer and use it in GitHub Desktop.
#include <stdio.h>
// first couple of triangular numbers
// http://en.wikipedia.org/wiki/Triangular_number
const int triag[] = {0, 1, 3, 6, 10, 15, 21};
// returns numbers of elements in first `h` rows of pascal's triangle that are
// not divisible by 7
// http://projecteuler.net/problem=148
long not7(long h) {
long n; // current number of elements not divisible by 7
long d; // current digit of `h` in base 7 representation
long b; // current base (7^(number of digits handled already))
// iterate through the digits of `h` in base 7 from right to left
for (n = 0, b = 1; h > 0; h /= 7, b *= 28) {
d = h % 7;
n = n * (d+1) + triag[d] * b;
}
return n;
}
int main() {
long h = 1e9;
long n = not7(h);
printf("not divisible by 7 in %ld rows: %ld\n", h, n);
}
@wellle
Copy link
Author

wellle commented Jul 20, 2013

Example invocation:

gcc -O3 -std=c99 pascal7.c -o pascal7 && time ./pascal7
not divisible by 7 in 1000000000 rows: 2129970655314432
./pascal7  0.00s user 0.00s system 56% cpu 0.003 total

So for comparison I propose the following benchmark of 10M different iterations:

int main() {
    long n = 0;
    for (long h = 0; h <= 1e9; h += 100) {
        n += not7(h) % 2;
    }
    printf("sum %ld\n", n);
}

For example:

gcc -O3 -std=c99 pascal7.c -o pascal7 && time ./pascal7
sum 22245
./pascal7  0.27s user 0.00s system 99% cpu 0.273 total

If it takes too long, try fewer iterations with h += 1000 etc.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment