Contest problems rated 1,000 to 1,200 about numbers too big to build. The move: never build the number; track its last digit, the exponents of its primes, or add each divisor once to its multiples.
This tent holds problems rated 1,000 to 1,200, and most hide a number that no program can hold. The first is a power with an exponent of 10^12, and the second is a tick length found from the differences of a list. The next is a least common multiple of 100,000 cycles. Then come a factorial of a size up to 10^12, the pairs of primes below 10^7, and divisor sums up to 200,000.
The literal route is to build the number and then read a fact from it. The limits forbid that, so the fact must come from somewhere smaller.
| Problem | The number you must not build | What you track instead |
|---|---|---|
| Last digit of a power | b to the power e, with e up to 10^12 | the last digit, which cycles |
| Least common multiple modulo | a product with hundreds of thousands of digits | the highest exponent of each prime |
| Trailing zeros of a factorial | 100,000! alone has 456,574 digits | the number of factors of 5 |
| Sum of divisors of every number | trial division: up to 59,528,927 steps | a sieve: 2,472,113 steps |
For a factorial, a trailing zero is a factor of 10, which is a 5 and a 2. Factors of 2 are plentiful, so the factors of 5 decide the count. Divide by 5, add, and repeat.
Exercise · Predict the output: Count the zeros of 130!. This adds the multiples of 5, then of 25, then of 125, by dividing n by 5 again and again. What does it print?
n = 130
zeros = 0
while n > 0:
n //= 5
zeros += n
print(zeros)Ask which single fact about the huge number the answer needs, and find the smallest thing that keeps it.
The last digit of a product depends only on the last digits of the factors. So the last digit of a power depends only on the last digit of the base. The factors of 5 in a factorial are counted by dividing, and the least common multiple is fixed by the highest exponent of each prime. Each fact is small, and each one is exact.
Keep only the fact the answer needs about the huge number, in a form that stays small and exact: a digit, a count or an exponent per prime.
The last digit of a power repeats. The digit 2 gives 2, 4, 8, 6, 2, 4, 8, 6, and so on. Every cycle has length 1, 2 or 4, so reduce the exponent to a number from 1 to 4. The shift by one matters: an exponent that is a multiple of 4 must land on 4, not on 0.
The last digit of a power repeats in a cycle of at most four, so reduce the exponent to a place from one to four.
Exercise · Find the bug: The exponent that lands on zero. This returns the last digit of base to the power exponent. It reduces the exponent to the cycle of four, then multiplies that many times modulo 10. Which line is wrong?
def last_digit(base, exponent):
digit = base % 10
reduced = exponent % 4
result = 1
for _ in range(reduced):
result = result * digit % 10
return resultBits and maths taught remainders, divisibility and the sieve. Common classes, felt showed what n log n costs, and Counting operations taught you to count a loop. This tent puts all three under a limit, and the edges move from the idea to the arithmetic.
The first edge is the modulus. The least common multiple modulo 1,000,000,007 cannot be folded pair by pair, because a fold divides by the greatest common divisor, and a remainder cannot be divided. Keep the highest exponent of each prime, and take the modulus only while you multiply them.
The second edge is a repeated factor. A product of the distinct cycles counts a shared factor twice. For 4 and 6 the least common multiple is 12, and the product is 24.
The third edge is the sieve. The divisor d is added to n / d multiples, and those counts add up to about n ln n. For 200,000 numbers that is 2,472,113 additions, against up to 59,528,927 steps of trial division.
Multiplying the distinct cycles counts a shared factor twice; the least common multiple keeps the highest exponent of each prime.
Exercise · Break it: The factor that is counted twice. Campaign cycles are given in days. This finds when they all line up by multiplying the distinct cycles, modulo 1,000,000,007. Find an input where it is wrong.
def lcm_mod(cycles):
result = 1
ordered = sorted(cycles)
for i in range(len(ordered)):
if i > 0 and ordered[i] == ordered[i - 1]:
continue
result = result * ordered[i] % 1000000007
return resultThe limit names the fact to track.
| Limit | What it rules out | What fits |
|---|---|---|
| an exponent up to 10^12 | the power, or a loop over the exponent | the last digit and its cycle |
| a size up to 10^12 | the factorial, or a loop over 1 to n | about 18 divisions by 5 |
| cycles up to 10^6 | an exact product | a sieve of smallest primes, exponents per prime |
| a limit of 2 x 10^5 and a value for each number | trial division for each | a sieve that adds each divisor to its multiples |
The full treatment is in Fast I/O and stress testing. Many queries on lines of two numbers read as pairs, and the answers go out joined, once.
import sys
def main():
data = sys.stdin.read().split()
q = int(data[0])
out = []
for i in range(q):
digit = int(data[1 + 2 * i]) % 10
reduced = (int(data[2 + 2 * i]) - 1) % 4 + 1
result = 1
for _ in range(reduced):
result = result * digit % 10
out.append(str(result))
sys.stdout.write("\n".join(out) + "\n")
main()import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int q = Integer.parseInt(in.readLine().trim());
StringBuilder out = new StringBuilder();
for (int i = 0; i < q; i++) {
StringTokenizer st = new StringTokenizer(in.readLine());
int digit = (int) (Long.parseLong(st.nextToken()) % 10);
long exponent = Long.parseLong(st.nextToken());
int reduced = (int) ((exponent - 1) % 4 + 1);
int result = 1;
for (int k = 0; k < reduced; k++) result = result * digit % 10;
out.append(result).append('\n');
}
System.out.print(out);
}
}#include <iostream>
#include <string>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int q;
cin >> q;
string out;
for (int i = 0; i < q; i++) {
long long base, exponent;
cin >> base >> exponent;
int digit = (int)(base % 10);
int reduced = (int)((exponent - 1) % 4 + 1);
int result = 1;
for (int k = 0; k < reduced; k++) result = result * digit % 10;
out += to_string(result) + "\n";
}
cout << out;
}const data = require("fs").readFileSync(0, "utf8").split(/\s+/).filter(Boolean);
const q = Number(data[0]);
const out = [];
for (let i = 0; i < q; i++) {
const digit = Number(BigInt(data[1 + 2 * i]) % 10n);
const reduced = Number((BigInt(data[2 + 2 * i]) - 1n) % 4n) + 1;
let result = 1;
for (let k = 0; k < reduced; k++) result = (result * digit) % 10;
out.push(String(result));
}
process.stdout.write(out.join("\n") + "\n");The bases and exponents reach 10^12, which is above 2^31 and above what a JavaScript number holds exactly for products, so the reading uses 64-bit values or BigInt.
Exercise · Put it in order: Count the factors of five. Arrange the lines into a function that returns the number of trailing zeros of n factorial.
def trailing_zeros(n):
zeros = 0
while n > 0:
n //= 5
zeros += n
return zeros
zeros += n // 5Building the factorial is the slow twin, and it only works for small n. The fast version below divides once and forgets the multiples of 25 and above.
import math
import random
def fast_zeros(n):
return n // 5
def slow_zeros(n):
digits = str(math.factorial(n))
return len(digits) - len(digits.rstrip("0"))
bad = 0
first = None
for seed in range(1000):
n = random.Random(seed).randint(0, 200)
if fast_zeros(n) != slow_zeros(n):
bad += 1
if first is None:
first = (seed, n)
print("first difference", first)
print(bad, "of 1000 inputs differ")
smallest = 0
while fast_zeros(smallest) == slow_zeros(smallest):
smallest += 1
print("smallest failing n", smallest)The run prints first difference (0, 98) and 868 of 1000 inputs differ, then smallest failing n 25. Random n from 0 to 200 fails often. Trying n from 0 upwards gives the smallest case at once: 25! has 6 zeros, and one division finds only 5.
Problems rated 1,000 to 1,200 use a classic fact, so the idea is known. The edge is what fails: a multiple of 4, the value 0, a modulus before a division, and a 32-bit overflow. Spend about 20 minutes on each, and write a stress test against a slow version that works for small inputs.
The first two work on one number each: the last digit of a power, and the greatest common divisor of differences. The next two work on factors: a least common multiple, and the factors of 5 in a factorial. The last two use a sieve: the primes below a limit, and a value for every number at once.
For each problem, write the fact you track in one line before you code, and the largest number it ever holds. If that number is above 2 x 10^9, use a 64-bit type.
Checkpoint · Number basics
Q1/5 What is the last digit of 7 to the power 10^12?
Answer: C
The last digit of the powers of 7 cycles through 7, 9, 3, 1. The exponent 10^12 is a multiple of 4, so it sits at the fourth place of the cycle, which is 1.
Q2/5 How many trailing zeros does 130! have?
Answer: C
130 / 5 = 26, 130 / 25 = 5 and 130 / 125 = 1 with whole division. 26 + 5 + 1 = 32.
Q3/5 A campaign has cycles of 4 and 6 days. When do they line up again, and what does the product of the distinct cycles give?
Answer: B
The cycles share the factor 2, so the product counts it twice. The least common multiple keeps the highest exponent of each prime: 4 x 3 = 12.
Q4/5 About how many steps does a divisor sieve take for the numbers up to 200,000?
Answer: B
The multiples number n / 1 + n / 2 + ... + n / n, which is about n ln n. The exact count here is 2,472,113.
Q5/5 A fast trailing-zero function returns n / 5. A stress test with n from 0 upwards finds the first difference at which n?
Answer: C
25! has 6 zeros, and 25 / 5 = 5. Every smaller n has the same count either way.
Review cards from this lesson.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.