Java number programs for SDET 

This is part two of the number programs set: GCD and LCM, digit programs, recursion, and number-system conversions. They look simple, but each has a trap interviewers like to probe — integer overflow in LCM, a wrong answer for zero, or recursion that breaks the second time it's called. Every program was compiled and run; the outputs are real. Part one (reverse, prime, palindrome, Armstrong): Java Number Programs Part 1.

Advertisement

1. GCD (HCF) ⭐

The greatest common divisor is the largest number that divides both numbers.

Brute force — O(min(a, b))

static int gcdLoop(int a, int b) {
    int g = 1;
    for (int i = 1; i <= Math.min(a, b); i++)
        if (a % i == 0 && b % i == 0) g = i;
    return g;
}
// gcdLoop(48, 18) → 6

Euclid's algorithm — O(log n)

static int gcd(int a, int b) {
    while (b != 0) {
        int t = b;
        b = a % b;
        a = t;
    }
    return Math.abs(a);
}
// gcd(48, 18) → 6,   gcd(17, 5) → 1,   gcd(0, 7) → 7

static int gcdRecursive(int a, int b) {
    return b == 0 ? Math.abs(a) : gcdRecursive(b, a % b);
}

Why it works: the GCD of a and b equals the GCD of b and a % b. For 48 and 18: (48, 18) → (18, 12) → (12, 6) → (6, 0), so the answer is 6. Show the loop first if asked, then Euclid as the optimization.

2. LCM — and the Overflow Trap

LCM = a × b ÷ GCD. Written naively with int, the multiplication overflows before the division:

int a = 1_000_000, b = 999_999;
a * b / gcd(a, b)                        // → -728379968   ❌ overflowed

static long lcm(int a, int b) {
    return (long) a / gcd(a, b) * b;     // divide first, then multiply in long
}
// lcm(48, 18) → 144,   lcm(1_000_000, 999_999) → 999999000000   ✅

Dividing by the GCD before multiplying keeps the intermediate value small, and long holds the result.

3. Sum of Digits

static int sumOfDigits(int n) {
    int s = 0;
    for (n = Math.abs(n); n > 0; n /= 10) s += n % 10;
    return s;
}

static int sumOfDigitsRecursive(int n) {
    return n == 0 ? 0 : n % 10 + sumOfDigitsRecursive(n / 10);
}
// both: 52749 → 27

4. Smallest and Largest Digit

static int[] minMaxDigit(int n) {
    n = Math.abs(n);
    int min = 9, max = 0;
    do {                                   // do-while so 0 is processed as a digit
        int d = n % 10;
        min = Math.min(min, d);
        max = Math.max(max, d);
        n /= 10;
    } while (n > 0);
    return new int[]{min, max};
}
// 52749 → [2, 9],   0 → [0, 0]

With a plain while (n > 0) loop, the input 0 never enters the loop and returns smallest = 9, largest = 0 — wrong. The do-while fixes it.

5. Reverse a Number With Recursion

static int reverseRecursive(int n, int rev) {
    return n == 0 ? rev : reverseRecursive(n / 10, rev * 10 + n % 10);
}
// reverseRecursive(1234, 0) → 4321, and again → 4321

Many tutorials store the result in a static int rev field. It works once — then the next call keeps adding to the old value. We ran that version twice: the first call gave 4321, the second 43214321. Passing the partial result as a parameter keeps the method self-contained. (Each step builds 4 → 43 → 432 → 4321.)

static void printAscending(int n) {
    if (n == 0) return;                // base case
    printAscending(n - 1);             // recurse first…
    System.out.print(n + " ");         // …then print → 1 2 3 4 5
}

static void printDescending(int n) {
    if (n == 0) return;
    System.out.print(n + " ");         // print first…
    printDescending(n - 1);            // …then recurse → 5 4 3 2 1
}

The only difference is whether the print happens before or after the recursive call — a nice way to show you understand the call stack. Every recursion needs a base case; without it you get a StackOverflowError.

7. Decimal to Binary and Back

static String toBinary(int n) {
    if (n == 0) return "0";
    StringBuilder sb = new StringBuilder();
    for (; n > 0; n /= 2) sb.append(n % 2);   // remainders, least significant first
    return sb.reverse().toString();
}
// 13 → "1101",   0 → "0"

static int toDecimal(String binary) {
    int result = 0;
    for (char c : binary.toCharArray()) result = result * 2 + (c - '0');
    return result;
}
// "1101" → 13

Built-ins for real code: Integer.toBinaryString(13) and Integer.parseInt("1101", 2) — mention them, but interviewers usually want the manual version. toDecimal uses Horner's method (multiply by 2 and add each bit) instead of powers of 2.

8. Neon Number

static boolean isNeon(int n) { return sumOfDigits(n * n) == n; }
// 9 → 9² = 81 → 8 + 1 = 9 ✓
// Neon numbers up to 10,000: [0, 1, 9]

There are only three — worth knowing if the interviewer asks you to "print all Neon numbers".

9. Power With Recursion

static long power(int base, int exp) {
    return exp == 0 ? 1 : base * power(base, exp - 1);
}
// power(2, 10) → 1024

Fibonacci is covered in part one — prefer the iterative version there; the naive recursive one is exponential.

Complexity Summary

Program Time
GCD by loop O(min(a, b))
GCD by Euclid, LCM O(log min(a, b))
Digit sum, min/max digit, reverse, binary conversion O(number of digits)
Print 1..N, power (recursive) O(n) time and O(n) stack

Watch the call stack grow and unwind in the recursive programs — and Euclid's pairs shrink — in the Java Code Visualizer.

From the Interview Room

Java has been the language of every automation framework I've worked with — Selenium, TestNG, POM classes and Apache POI for Excel data. Interviews for automation roles regularly include basic programs like this one, often followed by a question on OOP concepts. Practice writing it by hand and explaining how you'd test it. On Canolog, the many forms and screens across sales, inventory, finance and service are where keeping page details in POM classes and reusable steps in a business library paid off. Watch for integer overflow when numbers get large.

📚 Official documentation: dev.java: Learn Java (Oracle) · Java 21 API documentation

Frequently Asked Questions

How do you find the GCD of two numbers?

Euclid's algorithm: replace (a, b) with (b, a % b) until b is 0; a is the GCD. The brute-force loop from 1 to min(a, b) also works but is slower.

How do you find the LCM?

a / gcd(a, b) * b — divide first and use long to avoid integer overflow.

How do you reverse a number using recursion?

Pass the partial result as a parameter: reverse(n / 10, rev * 10 + n % 10) until n is 0. Avoid static fields, which break on the second call.

How do you convert decimal to binary?

Divide by 2 repeatedly, collect the remainders and reverse them — or use Integer.toBinaryString().

What is a Neon number?

A number equal to the sum of the digits of its square. Only 0, 1 and 9 qualify.

What is a base case in recursion?

The condition that stops the recursion (such as n == 0). Without it the method calls itself until the stack overflows.