# Scala algorithm: Count factors/divisors of an integer

Published , last updated

## Algorithm goal

A number \(y\) is a factor of \(x\) if \(x\) is divisible by \(y\). Find the number of distinct factors of a number \(x\).

For example, 2 has two factors: \(1\) and \(2\). 16 has 5 factors: \(1\), \(2\), \(4\), \(8\), and \(16\).

This problem is similar to the codility problem CountFactors - Count factors of given number n.

1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | โฆ | 15 | 16 | Total count | |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|

Divides 16? | โ | โ | โ | โ | โ | โ | โ | โ | โ | โ | โ | โ | 5 |

Factor count so far | 1 | 2 | 2 | 3 | 3 | 3 | 3 | 4 | 4 | 4 | 4 | 5 |

## Test cases in Scala

## Algorithm in Scala

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

## Explanation

In a brute-force approach, for number \(n\), we can check for all numbers that are divisible, up to \(n\).

However, there is a more efficient approach, in particular if we consider that for every factor that is under \(\sqrt{n}\), there a corresponding factor to be counted that is above \(\sqrt{n}\), meaning every divisor under the square root has a corresponding divisor above it - 2 divisors. (this is ยฉ from www.scala-algorithms.com)

## Scala concepts & Hints

### Collect

'collect' allows you to use Pattern Matching, to filter and map items.

### Pattern Matching

Pattern matching in Scala lets you quickly identify what you are looking for in a data, and also extract it.

### Range

The

`(1 to n)`

syntax produces a "Range" which is a representation of a sequence of numbers.### View

The

`.view`

syntax creates a structure that mirrors another structure, until "forced" by an eager operation like .toList, .foreach, .forall, .count.