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

Source code in the nim programming language

proc sum35(n: int): int =
  for x in 0 ..< n:
    if x mod 3 == 0 or x mod 5 == 0:
      result += x

echo sum35(1000)


import bigints

proc sumMults(first: int32, limit: BigInt): BigInt =
  var last = limit - 1
  last -= last mod first
  (last div first) * (last + first) div 2

proc sum35(n: BigInt): BigInt =
  result = sumMults(3, n)
  result += sumMults(5, n)
  result -= sumMults(15, n)

var x = 1.initBigInt
while x < "1000000000000000000000000000000".initBigInt:
  echo sum35 x
  x *= 10


  

You may also check:How to resolve the algorithm Pernicious numbers step by step in the D programming language
You may also check:How to resolve the algorithm Harshad or Niven series step by step in the Modula-2 programming language
You may also check:How to resolve the algorithm Guess the number step by step in the Racket programming language
You may also check:How to resolve the algorithm Write entire file step by step in the V (Vlang) programming language
You may also check:How to resolve the algorithm Best shuffle step by step in the AWK programming language