Scala algorithm: In a range of numbers, count the numbers divisible by a specific integer

Published , last updated

Algorithm goal

In a range $$5$$ to $$15$$, there are $$4$$ numbers divisible by $$n = 3$$: $$6$$, $$9$$, $$12$$ and $$15$$. Compute this for a generic $$n$$ (all non-negative numbers)

In Codility, there is a similar problem 'CountDiv'.

Algorithm in Scala

13 lines of Scala (compatible versions 2.13 & 3.0), showing how concise Scala can be!

Explanation

A brute-force method will have a complexity that depends strictlyon the size of the input number.

Notice however that the count of numbers divisible by$$3$$, up to $$15$$, is $$5$$ ($$3, 6, 9, 12, 15$$). If we do that with respect to a range, we need to just take the difference between counts up to the end of the range, and the counts up to the start of the range (excluding the number itself). (this is © from www.scala-algorithms.com)

Also if the number $$0$$ is in range, count is increased by 1 because $$0$$ is divisible by all numbers (except $$0$$, of course).

Scala concepts & Hints

1. Range

The (1 to n) syntax produces a "Range" which is a representation of a sequence of numbers.

assert((1 to 5).toString == "Range 1 to 5")

assert((1 to 5).reverse.toString() == "Range 5 to 1 by -1")

assert((1 to 5).toList == List(1, 2, 3, 4, 5))


Scala Algorithms: The most comprehensive library of algorithms in standard pure-functional Scala

Think in Scala & master the highest paid programming language in the US

Scala is used at many places, such as AirBnB, Apple, Bank of America, BBC, Barclays, Capital One, Citibank, Coursera, eBay, JP Morgan, LinkedIn, Morgan Stanley, Netflix, Singapore Exchange, Twitter.

Study our 92 Scala Algorithms: 6 fully free, 74 published & 18 upcoming

Fully unit-tested, with explanations and relevant concepts; new algorithms published about once a week.

Explore the 21 most useful Scala concepts

To save you going through various tutorials, we cherry-picked the most useful Scala concepts in a consistent form.