How to resolve the algorithm Sum multiples of 3 and 5 step by step in the PL/I 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 PL/I 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 PL/I programming language
Source code in the pl/i programming language
threeor5: procedure options (main); /* 8 June 2014 */
declare (i, n) fixed(10), sum fixed (31) static initial (0);
get (n);
put ('The number of multiples of 3 or 5 below ' || trim(n) || ' is');
do i = 1 to n-1;
if mod(i, 3) = 0 | mod(i, 5) = 0 then sum = sum + i;
end;
put edit ( trim(sum) ) (A);
end threeor5;
sum35_demo: proc options (main);
dcl limit fixed bin;
limit = 1000;
put skip list ('Sum of all multiples of 3 and 5 below', limit);
put skip edit ('Sum = ', sum35(limit)) ((a),(f(6)));
put skip edit ('Also: ', sum35alt(limit)) ((a),(f(6)));
stop;
sum35:
proc(limit) returns (float bin);
dcl
(limit, i) fixed bin,
sum float bin;
sum = 0;
do i=1 to (limit-1);
if mod(i,3) = 0 | mod(i,5) = 0 then
sum = sum + i;
end;
return (sum);
end sum35;
sum35alt:
proc(limit) returns (float bin);
dcl
limit fixed bin,
sum float bin;
sum = sum_of_multiples(3, limit) +
sum_of_multiples(5, limit) -
sum_of_multiples(15, limit);
return (sum);
end sum35alt;
sum_of_multiples:
proc(n, limit) returns (float bin);
dcl
(n, limit, i) fixed bin,
m float bin;
m = (limit - 1) / n;
return (n * m * (m + 1) / 2);
end sum_of_multiples;
end sum35_demo;
You may also check:How to resolve the algorithm Pseudo-random numbers/Middle-square method step by step in the Wren programming language
You may also check:How to resolve the algorithm Iterated digits squaring step by step in the ALGOL 68 programming language
You may also check:How to resolve the algorithm String matching step by step in the D programming language
You may also check:How to resolve the algorithm SEDOLs step by step in the Potion programming language
You may also check:How to resolve the algorithm Determine if a string is numeric step by step in the Icon and Unicon programming language