Lesson 12 of 34 · Methods
Boss: The Java Number Oracle
Vex the Clockwork Oracle blocks the way. Every test you pass deals damage — pass them all to defeat it and claim a loot chest.
At the top of a tower of grinding gears sits Vex the Clockwork Oracle, who answers only travellers fluent in the language of numbers. Each riddle you solve jams one of its cogs — build a toolbox of small, sharp methods and bring the whole machine to a halt.
Battle plan
This fight combines everything from Chapter 2: small static methods that call each other, loops, % for divisibility, and recursion.
- A prime is a whole number greater than 1 whose only divisors are 1 and itself: 2, 3, 5, 7, 11, 13… You only need to test divisors up to the square root: if
nhad a divisor larger than√n, it would also have one smaller than√n. Testingd * d <= navoids doubles entirely. - The greatest common divisor follows Euclid's 2,300-year-old rule:
gcd(a, 0) = aandgcd(a, b) = gcd(b, a % b). For examplegcd(48, 18) → gcd(18, 12) → gcd(12, 6) → gcd(6, 0) = 6. - The least common multiple comes straight from the GCD:
lcm(a, b) = a / gcd(a, b) * b. Dividing first keeps the intermediate value small. - The digital root keeps summing digits until one digit is left:
493193 → 29 → 11 → 2.
Assignment
Write six static methods in Main:
isPrime(int n)—trueifnis prime. Anything below 2 (including 0 and negatives) is not prime.nextPrime(int n)— the smallest prime strictly greater thann:nextPrime(7)is11,nextPrime(-5)is2.gcd(int a, int b)— the greatest common divisor of two non-negative ints, written recursively:gcd(48, 18)is6,gcd(7, 0)is7.lcm(int a, int b)— the least common multiple, computed withgcd:lcm(4, 6)is12. If either argument is0, return0.digitSum(long n)— the sum of the digits of a non-negativelong:digitSum(9876543210L)is45.digitalRoot(long n)— repeatdigitSumuntil a single digit remains:digitalRoot(493193)is2,digitalRoot(0)is0.
Every passing test cracks one of Vex's gears. Break all ten to win.
Premium lesson
Unlock the full Learn Java course
- All 34 lessons, bosses and quizzes — lifetime access
- One payment of $35, no subscription
- Finish within 30 days and claim $10.50 (30%) back
Want more than one course?
The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.
Keep learning
Need a quick reminder? The Java cheat sheet has every topic of Learn Java on one page.
Lesson last updated on .