How to resolve the algorithm Sum multiples of 3 and 5 step by step in the XPL0 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 XPL0 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 XPL0 programming language

Source code in the xpl0 programming language

include c:\cxpl\stdlib;

func Sum1;      \Return sum the straightforward way
int  N, S;
[S:= 0;
for N:= 1 to 999 do
    if rem(N/3)=0 or rem(N/5)=0 then S:= S+N;
return S;
];

func Sum2(D);   \Return sum of sequence using N*(N+1)/2
int  D;
int  Q;
[Q:= (1000-1)/D;
return Q*(Q+1)/2*D;
];

func Sum3(D);   \Return sum of sequence for really big number
string 0;       \don't terminate strings by setting most significant bit
int  D;         \divisor
int  I;
char P(40), Q(40), R(40);       \product, quotient, result
[StrNDiv("99999999999999999999", D, Q, 20);     \Q:= (1E20-1)/D
for I:= 0 to 17 do R(I):= ^0;                   \R:= D
R(18):= D/10 +^0;
R(19):= rem(0) +^0;
StrNMul(Q, R, P, 20);                           \P:= Q*R = Q*D
StrNAdd("00000000000000000001", Q, 20);         \Q:= Q+1
StrNMul(P+20, Q, R, 20);                        \R:= P*Q = Q*D*(Q+1)
StrNDiv(R, 2, Q, 40);                           \Q:= P/2 = Q*D*(Q+1)/2
return Q;                                       \(very temporary location)
];

char S(40), T;
[IntOut(0, Sum1);  CrLf(0);
 IntOut(0, Sum2(3) + Sum2(5) - Sum2(3*5));  CrLf(0);
StrNCopy(Sum3(3), S, 40);
StrNAdd(Sum3(5), S, 40);
T:= Sum3(3*5);
StrNSub(S, T, 40);
TextN(0, T, 40);  CrLf(0);
]

  

You may also check:How to resolve the algorithm Parsing/RPN calculator algorithm step by step in the EchoLisp programming language
You may also check:How to resolve the algorithm Text processing/1 step by step in the AutoHotkey programming language
You may also check:How to resolve the algorithm Sort using a custom comparator step by step in the Go programming language
You may also check:How to resolve the algorithm Box the compass step by step in the PowerShell programming language
You may also check:How to resolve the algorithm Optional parameters step by step in the Elixir programming language