Twelve problems on taking numbers apart and looping over them: digit sums, palindromes, powers of two, divisors, primes, the LCM and Fibonacci numbers.
- Sum of digits allows negative numbers: take
absfirst. The second Sum of digits goes up to 10¹⁸:long long. - Three-digit palindromes has no input: loop from 100 to 999, and a three-digit number is a palindrome when its first digit equals its last.
- Degree 2: halve
xwhile it is even; it was a power of two exactly when 1 is left. - Divisors, Common divisors and Prime number: with numbers up to 10⁵, a
loop up to
nis fast enough, and the √n loop is faster still. - Coprime numbers and LCM: Euclid's loop from the lesson gives the gcd; the
LCM is
a / gcd · b. - Fibonacci and Fibonacci 2: carry the last two numbers forward in
long long. In Fibonacci 2,A = 1is both F₁ and F₂ — the answer the tests expect is 1. - Next year comes last: a year has at most five digits here, so its digit sum
can be written out with
/and%, one digit at a time, inside the loop over the years.