ðŸŽ‰ Exercism Research is now launched. Help Exercism, help science and have some fun at research.exercism.io ðŸŽ‰

Panya's solution

to Sum Of Multiples in the PureScript Track

Published at Jul 13 2018 · 0 comments
Instructions
Test suite
Solution

Note:

This solution was written on an old version of Exercism. The tests below might not correspond to the solution code, and the exercise may have changed since this code was written.

Given a number, find the sum of all the multiples of particular numbers up to but not including that number.

If we list all the natural numbers up to but not including 20 that are multiples of either 3 or 5, we get 3, 5, 6 and 9, 10, 12, 15, and 18.

The sum of these multiples is 78.

Source

A variation on Problem 1 at Project Euler http://projecteuler.net/problem=1

Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

Main.purs

``````module Test.Main where

import Prelude

import SumOfMultiples (sumOfMultiples)
import Test.Unit (TestSuite, suite, test)
import Test.Unit.Assert as Assert
import Test.Unit.Console (TESTOUTPUT)
import Test.Unit.Main (runTest)

main :: forall eff
. Eff ( avar :: AVAR
, console :: CONSOLE
, testOutput :: TESTOUTPUT
| eff
)
Unit
main = runTest suites

suites :: forall e. TestSuite e
suites = do
suite "SumOfMultiples.sumOfMultiples" do
test "multiples of 3 or 5 up to 1" do
Assert.equal 0 (sumOfMultiples [3, 5] 1)

test "multiples of 3 or 5 up to 4" do
Assert.equal 3 (sumOfMultiples [3, 5] 4)

test "multiples of 3 up to 7" do
Assert.equal 9 (sumOfMultiples [3] 7)

test "multiples of 3 or 5 up to 10" do
Assert.equal 23 (sumOfMultiples [3, 5] 10)

test "multiples of 3 or 5 up to 100" do
Assert.equal 2318 (sumOfMultiples [3, 5] 100)

test "multiples of 3 or 5 up to 1000" do
Assert.equal 233168 (sumOfMultiples [3, 5] 1000)

test "multiples of 7, 13 or 17 up to 20" do
Assert.equal 51 (sumOfMultiples [7, 13, 17] 20)

test "multiples of 4 or 6 up to 15" do
Assert.equal 30 (sumOfMultiples [4, 6] 15)

test "multiples of 5, 6 or 8 up to 150" do
Assert.equal 4419 (sumOfMultiples [5, 6, 8] 150)

test "multiples of 5 or 25 up to 51" do
Assert.equal 275 (sumOfMultiples [5, 25] 51)

test "multiples of 43 or 47 up to 10000" do
Assert.equal 2203160 (sumOfMultiples [43, 47] 10000)

test "multiples of 1 up to 100" do
Assert.equal 4950 (sumOfMultiples [1] 100)

test "multiples of an empty list up to 10000" do
Assert.equal 0 (sumOfMultiples [] 10000)``````
``````module SumOfMultiples (sumOfMultiples) where

import Prelude (mod, (#), (==), (-))

import Data.Array (intersectBy, (..))
import Data.Foldable (sum)

sumOfMultiples :: Array Int -> Int -> Int
sumOfMultiples factors num =
intersectBy (\a b -> a `mod` b == 0) (1..(num - 1)) factors # sum``````