Monday, February 21, 2011

Project Euler 1



I'd like to get through as many of the Project Euler problems as I can in the evenings. I won't have a lot of time to dig through the next chapter of the GTK+ book until mid-March I figure and these problems can usually be knocked out fast once you figure out what has to be done.

Problem 1: http://projecteuler.net/index.php?section=problems&id=1

As long as you know how to test for remainders in a division you're golden. No real trick here.

1 comment:

  1. Fun(?) with number sequences:

    ( 1 + 2 + 3 + ... + X )
    = X(X+1)/2

    So,

    ( 3 + 6 + ... + L ) +
    ( 5 + 10 + ... + M ) -
    ( 15 + 30 + ... + N )
    = 3 * ( 1 + 2 + ... + L ) +
    5 * ( 1 + 2 + ... + M ) -
    15 * ( 1 + 2 + ... + N )
    = 3 * L(L+1)/2 + 5 * M(M+1)/2 - 15 * N(N+1)/2

    For L=999/3, M=999/5, N=999/15:

    // Sum all multiples of 3 or 5 below 1000
    // And, make sure not to count multiples of BOTH 3 and 5 twice!
    unsigned int limit = 1000;
    unsigned int L = (limit-1)/3;
    unsigned int M = (limit-1)/5;
    unsigned int N = (limit-1)/15;
    unsigned int total = (3*(L*(L+1))+5*(M*(M+1))-15*(N*(N+1)))/2;

    ReplyDelete