Counting
The counter pattern
Counting is the second of the two common loop tasks. It has the same three parts as summing, with one difference at the centre.Start a variable at 0 before the loop. Visit every item. When an item is worth counting, add ONE. Summing adds the item itself; counting adds 1 no matter how big the item is.
Counting factors
Write a function that accepts an integer parameter n and returns the number of factors of n.The loop tries every candidate from 1 up to n, and n % i == 0 asks whether i divides n exactly. Note the range: it has to reach n itself, because n is always a factor of n.