Task

The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n.

Show output for n = 1000.

This is is the same as Project Euler problem 1.

Extra credit: do this efficiently for n = 1e20 or higher.




include "cowgol.coh";
 
# sum multiples up to given input
interface SumMulTo(mul: uint32, to: uint32): (rslt: uint32);
 
# naive implementation
sub naiveSumMulTo implements SumMulTo is
    rslt := 0;
    var cur := mul;
    while cur < to loop
        rslt := rslt + cur;
        cur := cur + mul;
    end loop;
end sub;
 
# number theoretical implementation
sub fastSumMulTo implements SumMulTo is
    to := (to - 1)/mul;
    rslt := mul * to * (to + 1)/2;
end sub;
 
# sum multiples of 3 and 5 up to given number using given method
sub sum35(to: uint32, sum: SumMulTo): (rslt: uint32) is
    rslt := sum(3, to) + sum(5, to) - sum(15, to);
end sub;
 
print("Naive method: "); print_i32(sum35(1000, naiveSumMulTo)); print_nl();
print("Fast method:  "); print_i32(sum35(1000, fastSumMulTo)); print_nl();
 