How to resolve the algorithm Sum multiples of 3 and 5 step by step in the Cowgol programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Sum multiples of 3 and 5 step by step in the Cowgol programming language

Table of Contents

Problem Statement

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.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Sum multiples of 3 and 5 step by step in the Cowgol programming language

Source code in the cowgol programming language

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();

  

You may also check:How to resolve the algorithm Synchronous concurrency step by step in the UnixPipes programming language
You may also check:How to resolve the algorithm Abstract type step by step in the PARI/GP programming language
You may also check:How to resolve the algorithm Evolutionary algorithm step by step in the ColdFusion programming language
You may also check:How to resolve the algorithm Sierpinski carpet step by step in the Arturo programming language
You may also check:How to resolve the algorithm Parsing/RPN to infix conversion step by step in the Tcl programming language