Basic Number Logic

Solve one Java logic problem at a time, then flip for the complete explanation and program.

0/192 Known filtered set
Difficulty
Read Full Guide Question: 1 of 192

Java Logic Development · Chapter 01 Companion Article

Basic Number Logic

Sixteen foundational number-logic problems — parity checks, comparisons, swapping, summation formulas, powers, and range validation — converted into conditions, formulas, loops, and Java expressions. The same thinking patterns reappear later in arrays, strings, collections, and validation logic.

Overview

Basic number problems are useful for learning how to convert a requirement into conditions, formulas, loops, and Java expressions. Although many of these problems are small, the same thinking patterns appear later in arrays, strings, collections, validation logic, and real application code.

Core Logic Patterns Used in This Chapter

PatternUsed For
Modulo operatorEven/odd, remainder-based logic
Comparison operatorsPositive/negative, maximum, minimum
Temporary storageSwapping values
Arithmetic transformationSwap without third variable
Conditional operatorAbsolute value and simple decisions
Accumulator variableNumber summation
Mathematical formulaOptimized summation
LoopTables, powers, repeated calculations
Division and moduloQuotient and remainder
Logical ANDRange validation

1. Even or Odd Number

Concept

An integer is even if it is exactly divisible by 2, and odd if division by 2 leaves a non-zero remainder. The modulo operator % returns the remainder after division.

Core Condition

For an integer number, number % 2 == 0 means the number is even. Otherwise, it is odd.

Why This Logic Works

Every integer can be represented in one of these forms: 2 × k or 2 × k + 1, where k is another integer. Numbers of the first form are even. Numbers that leave a remainder after division by 2 are odd.

Example

For number = 27, the calculation 27 % 2 = 1 leaves a remainder, so 27 is odd.

Java Program

Java
public class EvenOddExample {
    public static void main(String[] args) {
        int number = 27;
        if (number % 2 == 0) {
            System.out.println(number + " is even.");
        } else {
            System.out.println(number + " is odd.");
        }
    }
}

Output

Output
27 is odd.

Dry Run

StepValue
number27
number % 21
1 == 0false
Executed blockelse
ResultOdd

Important Edge Cases

Zero

Zero is even because 0 % 2 = 0.

Negative Numbers

The same condition works for negative integers. For -8 % 2 = 0, therefore -8 is even.

Time Complexity

O(1) — only one modulo operation and one comparison are required.

Space Complexity

O(1) — no additional data structure is required.

Common Mistakes

  • Using division instead of modulo.
  • Checking number % 2 == 1 for odd numbers without considering negative values.
  • Treating zero as neither even nor odd.

A safer test for odd numbers is number % 2 != 0.

Interview Tip

When asked whether a number is even or odd, modulo is normally the clearest solution. Bitwise checking with number & 1 is possible, but modulo is easier to understand unless the interviewer specifically asks for a bitwise solution.

2. Positive, Negative or Zero

Concept

A number can belong to exactly one of three groups: positive, negative, or zero. The classification depends on comparison with zero.

Logic

number > 0 means positive. number < 0 means negative. If neither condition is true, the number must be zero.

Java Program

Java
public class NumberSignExample {
    public static void main(String[] args) {
        int number = -12;
        if (number > 0) {
            System.out.println("Positive number");
        } else if (number < 0) {
            System.out.println("Negative number");
        } else {
            System.out.println("Zero");
        }
    }
}

Output

Output
Negative number

Dry Run

Output
number = -12

-12 > 0  -> false
-12 < 0  -> true

Result: Negative number

Why else-if Is Useful

The three possible outcomes are mutually exclusive. Once Java finds a true condition, the remaining conditions do not need to be evaluated.

Edge Cases

Important values include Integer.MAX_VALUE, Integer.MIN_VALUE, and 0. The comparison logic works correctly for all three.

Time Complexity

O(1)

Space Complexity

O(1)

Common Mistake

Do not write independent conditions when only one result is expected unless there is a specific reason. For example, an if-else-if chain communicates the requirement more clearly than three separate if statements.

Interview Tip

This problem tests basic conditional reasoning. Explain the three mutually exclusive states instead of simply presenting the code.

3. Maximum of Two Numbers

Concept

Finding the maximum means determining which of two supplied values is greater. For a = 48 and b = 35, the maximum is 48.

Basic Logic

Compare a > b. If true, a is greater. Otherwise, b is greater or both values are equal.

Java Program

Java
public class MaximumOfTwo {
    public static void main(String[] args) {
        int a = 48;
        int b = 35;
        int maximum;
        if (a > b) {
            maximum = a;
        } else {
            maximum = b;
        }
        System.out.println("Maximum = " + maximum);
    }
}

Output

Output
Maximum = 48

Dry Run

VariableValue
a48
b35
a > btrue
maximum48

Equal Values

Suppose a = 20 and b = 20. The condition a > b becomes false, so b is assigned to maximum. The result is still correct because both numbers have the same value.

Ternary Alternative

For a simple comparison, int maximum = a > b ? a : b; is concise, but a normal if-else block can be easier for beginners to debug.

Library Alternative

Java provides Math.max(a, b). For production code, this is often preferable when no custom logic is required.

Time Complexity

O(1)

Space Complexity

O(1)

Common Mistake

Do not unnecessarily sort two values just to find the maximum. Sorting introduces extra logic for a problem that requires only one comparison.

Interview Tip

If an interviewer asks for logic without built-in methods, use a direct comparison. If built-in methods are allowed, Math.max communicates intent clearly.

4. Maximum of Three Numbers

Concept

The maximum of three values can be found by keeping track of the largest value encountered so far. For a = 17, b = 42, c = 29, the maximum is 42.

Efficient Approach

Start by assuming the first value is maximum: maximum = a. Compare b with maximum, then compare c with the updated maximum.

Java Program

Java
public class MaximumOfThree {
    public static void main(String[] args) {
        int a = 17;
        int b = 42;
        int c = 29;
        int maximum = a;
        if (b > maximum) {
            maximum = b;
        }
        if (c > maximum) {
            maximum = c;
        }
        System.out.println("Maximum = " + maximum);
    }
}

Output

Output
Maximum = 42

Dry Run

Output
maximum = 17

42 > 17  -> true   -> maximum = 42
29 > 42  -> false  -> maximum = 42

Final: maximum = 42

Why This Pattern Matters

The same technique scales naturally to arrays. Instead of writing complicated combinations such as a > b && a > c, you can maintain a running maximum. That technique is later used for:

  • Maximum array element
  • Minimum array element
  • Highest score
  • Largest transaction
  • Maximum temperature
  • Peak calculations

Alternative

int maximum = Math.max(a, Math.max(b, c)); is compact but hides the underlying comparison logic.

Equal Maximum Values

For 50, 50, 20, the result remains 50. The problem normally requires the maximum value, not which variable contains it.

Time Complexity

O(1)

Space Complexity

O(1)

Interview Tip

The running-maximum approach demonstrates logic that can later be generalized from three numbers to any number of values.

5. Minimum of Numbers

Concept

When multiple values are available, finding the minimum means identifying the smallest value among them. A common technique is to assume the first value is currently the minimum and update it whenever a smaller value appears. For 18, 7, 42, -3, 11, the minimum is -3.

Java Program

Java
public class MinimumNumber {
    public static void main(String[] args) {
        int[] numbers = {18, 7, 42, -3, 11};
        int minimum = numbers[0];
        for (int i = 1; i < numbers.length; i++) {
            if (numbers[i] < minimum) {
                minimum = numbers[i];
            }
        }
        System.out.println("Minimum = " + minimum);
    }
}

Output

Output
Minimum = -3

Dry Run

Starting value: minimum = 18

Current NumberCurrent MinimumUpdated Minimum
7187
4277
-37-3
11-3-3

Final minimum: -3

Why Start With the First Element?

Using minimum = 0 would produce incorrect results when all supplied numbers are positive. For example, in 4, 8, 15 zero is not present in the input, but the algorithm might incorrectly keep zero as the minimum. Initializing from actual input avoids this problem.

Important Edge Case

The array must contain at least one element before accessing numbers[0]. For reusable methods, empty input should be validated.

Time Complexity

For n values, O(n) — every number may need to be checked once.

Space Complexity

The minimum-search logic itself uses O(1) additional space.

Common Mistake

Sorting the complete collection just to retrieve the smallest element is unnecessary. Linear scanning is sufficient when only the minimum is needed.

Interview Tip

This is a fundamental tracking-variable pattern. The same logic is reused in many interview problems.

6. Swap Two Numbers

Concept

Swapping means exchanging the values stored in two variables. Before: a = 10, b = 25. After: a = 25, b = 10.

Why a Temporary Variable Is Needed

If you immediately write a = b, the original value of a is lost. A temporary variable protects that value.

Logic

Logic
temp = a
a = b
b = temp

Java Program

Java
public class SwapNumbers {
    public static void main(String[] args) {
        int a = 10;
        int b = 25;
        System.out.println("Before swap: a = " + a + ", b = " + b);
        int temp = a;
        a = b;
        b = temp;
        System.out.println("After swap: a = " + a + ", b = " + b);
    }
}

Output

Output
Before swap: a = 10, b = 25
After swap: a = 25, b = 10

Dry Run

Output
a = 10, b = 25

temp = a   -> temp = 10
a = b      -> a = 25
b = temp   -> b = 10

Time Complexity

O(1)

Space Complexity

O(1) — one temporary variable uses constant additional memory.

Practical Use

Swapping appears in algorithms such as:

  • Bubble sort
  • Selection sort
  • Quick sort partitioning
  • Array reversal
  • Two-pointer algorithms
  • Heap operations

Common Mistake

Incorrect sequence: a = b; b = a; — after the first statement, the original a has already been overwritten.

Interview Tip

Using a temporary variable is normally the safest and most readable solution. Avoid complicated tricks unless the interviewer explicitly asks for swapping without additional storage.

7. Swap Without Third Variable

Concept

Two integer values can be exchanged without declaring another variable. One arithmetic technique uses addition and subtraction.

Logic

Starting with a = 12, b = 30, perform:

Logic
a = a + b
b = a - b
a = a - b

Java Program

Java
public class SwapWithoutThirdVariable {
    public static void main(String[] args) {
        int a = 12;
        int b = 30;
        System.out.println("Before swap: a = " + a + ", b = " + b);
        a = a + b;
        b = a - b;
        a = a - b;
        System.out.println("After swap: a = " + a + ", b = " + b);
    }
}

Output

Output
Before swap: a = 12, b = 30
After swap: a = 30, b = 12

Dry Run

Output
a = 12, b = 30

a = 12 + 30 = 42
b = 42 - 30 = 12
a = 42 - 12 = 30

Final: a = 30, b = 12

Why It Works

After a = a + b, the new a contains information about both original values. Subtracting the old b retrieves the original a. The final subtraction retrieves the original b.

Important Limitation: Integer Overflow

The statement a = a + b can overflow when both values are large — the mathematical sum may exceed the range supported by int. Because of this, arithmetic swapping is normally not recommended for production Java code.

XOR Alternative

Integers can also be swapped using XOR:

Java
a = a ^ b;
b = a ^ b;
a = a ^ b;

This avoids arithmetic overflow but is less readable.

Best Practical Choice

In normal application code, prefer a temporary variable. No-third-variable swapping is mainly useful as a logic or interview exercise.

Time Complexity

O(1)

Space Complexity

O(1)

Interview Tip

Mention the overflow limitation of addition/subtraction swapping. That demonstrates stronger understanding than simply memorizing the three statements.

8. Absolute Value

Concept

Absolute value represents the distance of a number from zero, regardless of direction. Examples: |8| = 8, |-8| = 8, |0| = 0.

Basic Logic

If the number is negative, reverse its sign. Otherwise, keep it unchanged.

Java Program

Java
public class AbsoluteValueExample {
    public static void main(String[] args) {
        int number = -45;
        long absoluteValue = number < 0 ? -(long) number : number;
        System.out.println("Absolute value = " + absoluteValue);
    }
}

Output

Output
Absolute value = 45

Dry Run

Output
number = -45
number < 0        -> true
-(long) -45        -> 45

absoluteValue = 45

Why long Is Used

The int range is -2147483648 to 2147483647. The positive equivalent of -2147483648 is 2147483648, which cannot fit inside int. Casting to long before negation allows this value to be represented safely.

Built-In Method

Java provides Math.abs(number). This is appropriate in most normal code. However, Math.abs(Integer.MIN_VALUE) still returns a negative int because its positive equivalent cannot be represented by int.

Time Complexity

O(1)

Space Complexity

O(1)

Practical Uses

Absolute difference is commonly used for:

  • Distance calculations
  • Difference between values
  • Error measurement
  • Coordinate calculations
  • Threshold validation

Example: Math.abs(actual - expected)

Common Mistake

Do not blindly use number = -number for every negative int without considering Integer.MIN_VALUE.

Interview Tip

For basic questions, explain the sign check. For stronger answers, also mention the Integer.MIN_VALUE edge case.

9. Sum of Natural Numbers

Concept

Natural-number summation usually means adding consecutive positive integers from 1 to n. For n = 5, the sum is 1 + 2 + 3 + 4 + 5 = 15.

Loop Approach

A direct approach is to maintain an accumulator, sum = sum + i, for every value from 1 through n.

Mathematical Formula

The sum can also be calculated directly: n × (n + 1) / 2.

Why the Formula Works

For numbers 1, 2, 3, ..., n, pairing values from opposite ends produces repeated sums of n + 1. This leads to the formula n(n + 1) / 2.

Java Program

Java
public class NaturalNumberSum {
    public static void main(String[] args) {
        int n = 10;
        long sum = (long) n * (n + 1) / 2;
        System.out.println("Sum = " + sum);
    }
}

Output

Output
Sum = 55

Dry Run

Output
n = 10
10 x 11 / 2 = 110 / 2 = 55

Why Cast Before Multiplication?

The expression n * (n + 1) is calculated as int if both operands are int. It may overflow before the result is stored in long. Therefore (long) n * (n + 1) forces the multiplication to use long arithmetic.

Loop Alternative

Java
long sum = 0;
for (int i = 1; i <= n; i++) {
    sum += i;
}

This is useful when learning loops, but the formula is faster when only the final sum is required.

Complexity

Loop: time O(n), space O(1). Formula: time O(1), space O(1).

Input Validation

If the requirement defines natural numbers as positive integers, n should satisfy n >= 1. Some systems also include zero in natural numbers, so requirements should be clarified.

Interview Tip

When asked to optimize a summation problem, recognize whether a mathematical formula can replace iteration.

10. Sum of Even Numbers

Problem Definition

Find the sum of all even integers from 1 through n. For n = 10, even numbers are 2, 4, 6, 8, 10 and the sum is 30.

Loop Approach

Check every number with i % 2 == 0 and add matching values. A better loop can skip odd numbers completely using i += 2.

Mathematical Pattern

The first k positive even numbers are 2, 4, 6, ..., 2k. Their sum is k(k + 1). When the range is 1 through n, k = n / 2 because integer division gives the number of even values in the range.

Java Program

Java
public class EvenNumberSum {
    public static void main(String[] args) {
        int n = 10;
        long count = n / 2;
        long sum = count * (count + 1);
        System.out.println("Sum of even numbers = " + sum);
    }
}

Output

Output
Sum of even numbers = 30

Dry Run

Output
n = 10
count = 10 / 2 = 5
5 x 6 = 30

Example With Odd Upper Limit

For n = 9, even values are still 2, 4, 6, 8. Integer division gives 9 / 2 = 4, so the formula continues to work.

Loop Alternative

Java
long sum = 0;
for (int i = 2; i <= n; i += 2) {
    sum += i;
}

Complexity

Formula: O(1). Loop: O(n) — more precisely, the loop executes roughly n / 2 times, which still simplifies to O(n).

Common Mistake

Do not confuse sum of even numbers up to n with sum of the first n even numbers — these are different requirements. For the first n even numbers, n itself represents the count.

Interview Tip

Clarify whether n represents an upper range limit or the number of even terms before writing the algorithm.

11. Sum of Odd Numbers

Problem Definition

Find the sum of all odd integers between 1 and n. For n = 10, odd values are 1, 3, 5, 7, 9 and the sum is 25.

Mathematical Pattern

The sum of the first k odd numbers is . For a range from 1 through n, the number of odd values is (n + 1) / 2 using integer division.

Java Program

Java
public class OddNumberSum {
    public static void main(String[] args) {
        int n = 10;
        long count = ((long) n + 1) / 2;
        long sum = count * count;
        System.out.println("Sum of odd numbers = " + sum);
    }
}

Output

Output
Sum of odd numbers = 25

Dry Run

Output
n = 10
count = (10 + 1) / 2 = 11 / 2 = 5
5 x 5 = 25

Why the Pattern Works

Logic
1             = 1^2
1 + 3         = 2^2
1 + 3 + 5     = 3^2
1 + 3 + 5 + 7 = 4^2

Each new odd number expands the previous square into the next square.

Loop Alternative

Java
long sum = 0;
for (int i = 1; i <= n; i += 2) {
    sum += i;
}

Complexity

Formula: O(1). Loop: O(n).

Important Requirement Detail

For negative ranges, this formula is not applicable without redefining the problem. It assumes a positive range beginning at 1.

Interview Tip

Recognizing numeric patterns can eliminate unnecessary loops. Explain the count of odd numbers before applying the square formula.

12. Multiplication Table

Concept

A multiplication table repeatedly multiplies one fixed number by a sequence of integers. For 7: 7 × 1 through 7 × 10. This is a straightforward example of counted iteration.

Java Program

Java
public class MultiplicationTable {
    public static void main(String[] args) {
        int number = 7;
        for (int i = 1; i <= 10; i++) {
            System.out.println(number + " x " + i + " = " + number * i);
        }
    }
}

Output

Output
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70

Dry Run

For the first three iterations:

iCalculationResult
17 × 17
27 × 214
37 × 321

The loop continues until i becomes 11. At that point i <= 10 becomes false.

Important Variables

number

The fixed number whose table is generated.

i

Controls the multiplier and loop count.

Custom Range

A reusable version can accept a starting multiplier, ending multiplier, and table number — for example, 5 × 6 through 5 × 15. This demonstrates that the algorithm is not restricted to 1 through 10.

Time Complexity

If the table contains k entries, O(k). For a fixed table of 10 entries, it can technically be viewed as constant work, but O(k) better describes the generalized solution.

Space Complexity

O(1)

Common Mistakes

  • Using i < 10 when the table should include 10.
  • Incrementing the wrong variable.
  • Accidentally modifying the table number inside the loop.

Interview Tip

Simple loop questions often test boundary handling. Pay attention to starting value, ending value, and whether the limits are inclusive.

13. Power of a Number

Concept

For a non-negative integer exponent, power represents repeated multiplication. For 3⁴, the calculation is 3 × 3 × 3 × 3 = 81. Here 3 is the base, 4 is the exponent, and 81 is the result.

Basic Iterative Logic

Start with result = 1, then multiply result by the base exponent times.

Why Start With 1?

One is the multiplicative identity. For any value x, 1 × x = x. Starting with zero would make every multiplication remain zero.

Java Program

Java
public class PowerExample {
    public static void main(String[] args) {
        int base = 3;
        int exponent = 4;
        long result = 1;
        for (int i = 0; i < exponent; i++) {
            result *= base;
        }
        System.out.println("Result = " + result);
    }
}

Output

Output
Result = 81

Dry Run

Initial: result = 1

IterationCalculationresult
11 × 33
23 × 39
39 × 327
427 × 381

Exponent Zero

By definition x⁰ = 1 for non-zero x. The loop executes zero times, leaving result = 1, which naturally handles this case.

Negative Exponents

A negative exponent creates a fractional result — for example 2⁻² = 1 / 4. The current integer-based algorithm intentionally handles only exponent >= 0. A double-based implementation would be needed for negative exponents.

Math.pow Alternative

Java provides Math.pow(base, exponent). It returns a double. For integer-only logic problems, manual multiplication makes the algorithm easier to study.

Faster Approach

Exponentiation by squaring can reduce the complexity from O(exponent) to O(log exponent). For example, 2¹⁰ does not need ten separate multiplications if repeated squaring is used.

Time Complexity

Basic loop: O(exponent)

Space Complexity

O(1)

Common Mistake

Initializing result = 0 causes every positive exponent result to remain zero.

Interview Tip

Start with the simple iterative solution. If the exponent may be very large, discuss exponentiation by squaring as an optimization.

14. Square and Cube of Number

Concept

The square of a number is the number multiplied by itself once: square = n × n. The cube multiplies the number three times: cube = n × n × n.

Example

For n = 6: square 6 × 6 = 36, cube 6 × 6 × 6 = 216.

Java Program

Java
public class SquareCubeExample {
    public static void main(String[] args) {
        int number = 6;
        long square = (long) number * number;
        long cube = (long) number * number * number;
        System.out.println("Square = " + square);
        System.out.println("Cube = " + cube);
    }
}

Output

Output
Square = 36
Cube = 216

Dry Run

Output
number = 6
Square: 6 x 6 = 36
Cube:   6 x 6 x 6 = 216

Why Direct Multiplication Is Preferable Here

Using Math.pow(number, 2) works, but Math.pow returns double. For exact integer square and cube calculations, direct multiplication is simpler and avoids floating-point conversion.

Negative Number Behavior

For number = -3: square (-3) × (-3) = 9, cube (-3) × (-3) × (-3) = -27. The normal multiplication rules automatically produce the correct signs.

Overflow Consideration

Even long has a finite range. Large values can overflow during square or cube calculations. For arbitrary-size integer calculations, Java provides BigInteger.

Time Complexity

O(1)

Space Complexity

O(1)

Interview Tip

Casting before the first multiplication is useful when the input is int but the result is stored in long.

15. Quotient and Remainder

Concept

Integer division can produce two useful values: quotient, how many complete times the divisor fits into the dividend, and remainder, what remains after those complete divisions. For 29 ÷ 6, the quotient is 4 and the remainder is 5, because 29 = 6 × 4 + 5.

Java Operators

Division operator /. Modulo operator %.

Java Program

Java
public class QuotientRemainderExample {
    public static void main(String[] args) {
        int dividend = 29;
        int divisor = 6;
        int quotient = dividend / divisor;
        int remainder = dividend % divisor;
        System.out.println("Quotient = " + quotient);
        System.out.println("Remainder = " + remainder);
    }
}

Output

Output
Quotient = 4
Remainder = 5

Dry Run

Output
dividend = 29, divisor = 6
29 / 6 = 4
6 x 4 = 24
29 - 24 = 5

quotient = 4, remainder = 5

Fundamental Relationship

For integer division: dividend = divisor × quotient + remainder. For this example: 29 = 6 × 4 + 5.

Division by Zero

The divisor must never be zero. This causes ArithmeticException for integer division. A reusable method should validate divisor != 0 before calculating.

Integer Division Behavior

Java integer division removes the fractional portion. For 7 / 2, the result is 3, not 3.5. To obtain a decimal result, at least one operand must use a floating-point type.

Negative Numbers

Java allows negative operands. For example, -29 % 6 produces -5. Java's remainder has the same sign as the dividend when the result is non-zero.

Practical Uses of Remainder

Modulo logic appears in:

  • Even or odd detection
  • Circular indexing
  • Clock calculations
  • Digit extraction
  • Divisibility checks
  • Alternating patterns
  • Hashing-related calculations

Time Complexity

O(1)

Space Complexity

O(1)

Common Mistake

Do not assume integer division automatically produces a decimal result. int result = 5 / 2; produces 2.

Interview Tip

Be prepared to explain the relationship between quotient, remainder, dividend, and divisor instead of only naming the two operators.

16. Number Range Validation

Concept

Range validation determines whether a value falls between allowed lower and upper limits. Suppose a valid age must be between 18 and 60 inclusive. A value is valid only if both age >= 18 and age <= 60 are true.

Core Logic

Use logical AND: number >= minimum && number <= maximum. Both conditions must be true.

Java Program

Java
public class RangeValidation {
    public static void main(String[] args) {
        int number = 24;
        int minimum = 18;
        int maximum = 60;
        if (number >= minimum && number <= maximum) {
            System.out.println(number + " is within range " + minimum + " to " + maximum + ".");
        } else {
            System.out.println(number + " is outside the valid range.");
        }
    }
}

Output

Output
24 is within range 18 to 60.

Dry Run

Output
number = 24, minimum = 18, maximum = 60

24 >= 18  -> true
24 <= 60  -> true
true && true -> true

Result: 24 is accepted.

Inclusive Range

The condition number >= minimum && number <= maximum includes both boundary values. For a range 18 through 60, 18 is valid and 60 is also valid.

Exclusive Range

To exclude the boundaries: number > minimum && number < maximum. Now only values strictly between the limits are valid.

Mixed Boundary Rules

Minimum inclusive, maximum exclusive: number >= minimum && number < maximum. This style is common in:

  • Array indexes
  • Pagination
  • Date/time ranges
  • Loop boundaries

Why AND Is Required

Consider number >= minimum || number <= maximum. Using OR would usually make the condition almost always true. For a valid bounded range, the value must satisfy both lower and upper constraints.

Validate the Range Itself

When minimum and maximum come from external input, verify minimum <= maximum. A range such as minimum = 100, maximum = 20 is logically invalid.

Reusable Method

Java
public class RangeValidator {
    public static boolean isWithinRange(int number, int minimum, int maximum) {
        if (minimum > maximum) {
            return false;
        }
        return number >= minimum && number <= maximum;
    }

    public static void main(String[] args) {
        System.out.println(isWithinRange(35, 10, 50));
    }
}

Output

Output
true

Time Complexity

O(1)

Space Complexity

O(1)

Practical Uses

Range validation appears frequently in real applications:

  • Age validation
  • Percentage validation
  • Marks validation
  • Quantity limits
  • Price filters
  • Rating validation
  • Page-number validation
  • Retry limits
  • Configuration limits

Common Mistakes

  • Using OR instead of AND.
  • Using > when the minimum should be allowed.
  • Using < when the maximum should be allowed.
  • Forgetting to validate minimum and maximum themselves.

Interview Tip

Always clarify whether the boundaries are inclusive or exclusive. Many range-validation bugs come from incorrect boundary assumptions.

Important Java Operators Used in Basic Number Logic

OperatorMeaningExample
+Additiona + b
-Subtractiona - b
*Multiplicationa * b
/Divisiona / b
%Remaindera % b
>Greater thana > b
<Less thana < b
>=Greater than or equala >= b
<=Less than or equala <= b
==Equal toa == b
!=Not equal toa != b
&&Logical ANDa >= min && a <= max
||Logical ORa < min || a > max

Important Number Logic Patterns

1. Direct Comparison

Used when a decision depends on relative numeric values. Examples: maximum, minimum, positive or negative, range checking.

Java
if (a > b) {
    // Handle greater value
}

2. Remainder-Based Logic

Use modulo when the problem depends on divisibility. Typical form: number % divisor. Common uses: even or odd, divisibility, last digit, circular operations.

3. Running Value Tracking

Maintain the best value found so far, for example int maximum = numbers[0];, then update it when a better candidate appears. This pattern later becomes important in:

  • Array maximum
  • Array minimum
  • Stock-profit problems
  • Largest subarray calculations
  • Selection problems

4. Accumulator Pattern

An accumulator collects a result over multiple iterations.

Java
long sum = 0;
for (...) {
    sum += value;
}

Common uses: sum, count, product, average preparation, frequency calculations.

5. Mathematical Optimization

Before writing a loop, determine whether the same result can be calculated directly. Instead of summing 1 + 2 + 3 + ... + n, use n × (n + 1) / 2. This changes the time complexity from O(n) to O(1).

6. Boundary Validation

Many bugs occur at boundary values. For a range 10 to 50, test at least 9, 10, 11, 49, 50, 51. This verifies both inside and outside conditions.

Primitive Type Selection for Number Logic

Choosing an appropriate numeric type matters when calculations can become large.

TypeApproximate Use
byteVery small integer values
shortSmall integer values
intNormal integer calculations
longLarger integer calculations
floatLower-precision decimal calculations
doubleGeneral decimal calculations
BigIntegerArbitrarily large integers
BigDecimalPrecise decimal arithmetic

For most beginner number-logic problems, int is enough for input. Intermediate calculations may require long.

Integer Overflow

Java does not automatically stop integer overflow.

Java
int a = Integer.MAX_VALUE;
int b = a + 1;

The result wraps around to the negative side of the int range. This matters especially in:

  • Sum formulas
  • Powers
  • Squares
  • Cubes
  • Arithmetic swapping
  • Large multiplication

A common defensive technique is to promote the operation before multiplication:

Java
long result = (long) a * b;

Casting after multiplication may be too late because overflow may already have happened.

Formula vs Loop

Different problems can often be solved in more than one way.

ProblemLoopFormula/Direct Logic
Even/OddNot neededO(1)
Maximum of twoNot neededO(1)
Sum 1 to nO(n)O(1)
Sum even numbersO(n)O(1)
Sum odd numbersO(n)O(1)
Multiplication tableO(n)Normally requires iteration
PowerO(n) basicO(log n) optimized
Range validationNot neededO(1)

Use a loop when repeated processing is genuinely required. Use direct arithmetic when a reliable formula exists.

Input Validation Principles

Number logic becomes more reliable when assumptions are explicit.

Validate Divisors

Before dividend / divisor, ensure divisor != 0.

Validate Ranges

Before using minimum <= number && number <= maximum, ensure minimum <= maximum.

Validate Mathematical Domains

If a problem only supports positive n, n > 0 should be part of the requirement.

Validate Exponents

If an integer power algorithm only handles non-negative exponents, exponent >= 0 must be guaranteed or checked.

Basic Number Logic Edge Cases

Useful test values include:

Test ValueWhy It Matters
0Boundary between positive and negative
1Smallest common positive value
-1Small negative value
Even positiveParity test
Odd positiveParity test
Even negativeNegative parity
Odd negativeNegative parity
Equal valuesMaximum/minimum comparison
Integer.MAX_VALUEOverflow testing
Integer.MIN_VALUEAbsolute-value and overflow testing
Range minimumInclusive boundary
Range maximumInclusive boundary
Just below minimumInvalid boundary
Just above maximumInvalid boundary

Common Logic Mistakes in This Chapter

Using the Wrong Comparison Operator

Requirement: 18 or older. Correct: age >= 18. Incorrect: age > 18 — this rejects exactly 18.

Using OR Instead of AND for Range Checking

Incorrect: number >= minimum || number <= maximum. Correct: number >= minimum && number <= maximum.

Losing a Value During Swapping

Incorrect sequence: a = b; b = a; — both values may become identical. Protect the original value before overwriting it.

Starting a Product With Zero

Incorrect: int result = 0; result *= base; — any multiplication by zero remains zero. For repeated multiplication, initialize with result = 1.

Starting Minimum or Maximum With Arbitrary Values

Avoid assumptions such as minimum = 0 when zero may not exist in the input. Initialize tracking variables from actual input whenever possible.

Ignoring Integer Division

5 / 2 produces 2 when both operands are integers. For 2.5, use a floating-point operand.

Casting Too Late

Risky: long result = a * b; — if both a and b are int, overflow can happen before assignment. Safer: long result = (long) a * b;

Interview-Oriented Problem-Solving Checklist

Before coding a number-logic problem, identify:

  1. What are the inputs?
  2. What exact output is required?
  3. Are negative values allowed?
  4. Is zero valid?
  5. Are boundaries inclusive?
  6. Can values become larger than int?
  7. Is division by zero possible?
  8. Can a mathematical formula replace a loop?
  9. Does the problem require a value or its position?
  10. What happens when values are equal?
  11. Does the algorithm need integer or decimal arithmetic?
  12. Can the problem be solved in constant space?
  13. Are built-in methods allowed?
  14. Is readability more important than a clever shortcut?

Chapter Complexity Summary

TopicTypical TimeExtra Space
Even or OddO(1)O(1)
Positive, Negative or ZeroO(1)O(1)
Maximum of TwoO(1)O(1)
Maximum of ThreeO(1)O(1)
Minimum of Multiple NumbersO(n)O(1)
Swap Two NumbersO(1)O(1)
Swap Without Third VariableO(1)O(1)
Absolute ValueO(1)O(1)
Sum of Natural NumbersO(1) with formulaO(1)
Sum of Even NumbersO(1) with formulaO(1)
Sum of Odd NumbersO(1) with formulaO(1)
Multiplication TableO(n)O(1)
Power of NumberO(n) basicO(1)
Square and CubeO(1)O(1)
Quotient and RemainderO(1)O(1)
Number Range ValidationO(1)O(1)

Practice Variations

After understanding the basic implementations, useful variations include:

  • Check whether a number is divisible by both 3 and 5.
  • Determine whether two integers have the same sign.
  • Find the minimum of three numbers.
  • Find both minimum and maximum in one traversal.
  • Swap two long values.
  • Calculate absolute difference between two numbers.
  • Find the sum from m to n.
  • Find the sum of even values within a custom range.
  • Find the sum of odd values within a custom range.
  • Generate a multiplication table for a supplied start and end multiplier.
  • Calculate power without Math.pow.
  • Implement fast exponentiation.
  • Check whether square multiplication may overflow.
  • Validate quotient calculations before division.
  • Validate whether marks are between 0 and 100.
  • Clamp a number to a supplied minimum and maximum.
  • Determine whether two numeric ranges overlap.
  • Find the nearest boundary when a number falls outside a range.

Question Hint