How to resolve the algorithm Sum multiples of 3 and 5 step by step in the Wren 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 Wren 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 Wren programming language
Source code in the wren programming language
var sum35 = Fn.new { |n|
n = n - 1
var s3 = (n/3).floor
var s5 = (n/5).floor
var s15 = (n/15).floor
s3 = 3 * s3 * (s3+1)
s5 = 5 * s5 * (s5+1)
s15 = 15 * s15 * (s15+1)
return (s3 + s5 - s15)/2
}
System.print(sum35.call(1000))
import "./gmp" for Mpz
import "./fmt" for Fmt
var sumMultiples = Fn.new { |result, limit, f|
var m = Mpz.from(limit).sub(1).fdiv(f)
result.set(m).inc.mul(m).mul(f).rsh(1)
}
var limit = Mpz.one
var tempSum = Mpz.new()
var sum35 = Mpz.new()
var max = 25
Fmt.print("$*s $s", max + 1, "limit", "sum")
for (i in 0..max) {
Fmt.write("$*s ", max + 1, limit)
sumMultiples.call(tempSum, limit, 3)
sum35.set(tempSum)
sumMultiples.call(tempSum, limit, 5)
sum35.add(tempSum)
sumMultiples.call(tempSum, limit, 15)
sum35.sub(tempSum)
System.print(sum35)
limit.mul(10)
}
You may also check:How to resolve the algorithm Conditional structures step by step in the V programming language
You may also check:How to resolve the algorithm Strip a set of characters from a string step by step in the Logo programming language
You may also check:How to resolve the algorithm Repeat a string step by step in the Lingo programming language
You may also check:How to resolve the algorithm 21 game step by step in the BASIC programming language
You may also check:How to resolve the algorithm Window creation step by step in the JavaScript programming language