Definition
- Prime number – an integer greater than one whose only positive divisors are 1 and itself.
- Square-root optimization – divisors come in pairs multiplying to N, so if no divisor exists up to sqrt(N), none exists at all.
- Loop bound –
i * i <= navoids a floating-pointMath.sqrtand keeps the test in integers. - Even shortcut – two is the only even prime; after checking two, loop only over odd candidates starting at three.
- Complexity – O(sqrt(n)) time, O(1) space for the trial-division approach.
Imagine National Bank of India generating special indivisible token numbers for secure transactions. A token is valid only if it cannot be split evenly into smaller equal groups. Checking a token is like trying to divide a pile of coins into equal stacks of two, three, four, and so on. If no stack size up to the square root divides the pile evenly, the pile is indivisible, that is, prime.
Understanding the Concepts
What is a prime number?
A prime number is an integer greater than one that has no positive divisors other than one and itself. For example, 7 is prime because no number from 2 to 6 divides it evenly. 9 is not prime because 3 divides it.
Why check only up to the square root?
Divisors come in pairs that multiply to N. For 36, the pairs are (1,36), (2,18), (3,12), (4,9), (6,6). In every pair, one member is at most sqrt(N) and the other is at least sqrt(N). So if no divisor exists up to sqrt(N), none exists above it either. This reduces the work from O(n) to O(sqrt(n)).
How do you implement it in Java?
package com.bank.service;
public class PrimeChecker {
public static boolean isPrime(int n) {
if (n < 2) return false;
if (n == 2) return true; // only even prime
if (n % 2 == 0) return false; // eliminate all other evens
for (int i = 3; i * i <= n; i += 2) {
if (n % i == 0) return false;
}
return true;
}
public static void main(String[] args) {
// Validate secure token candidates for National Bank of India
int[] candidates = {2, 3, 4, 7, 9, 7919, 10000};
for (int c : candidates) {
System.out.println(c + " -> " + (isPrime(c) ? "PRIME" : "NOT PRIME"));
}
}
}
2 -> PRIME
3 -> PRIME
4 -> NOT PRIME
7 -> PRIME
9 -> NOT PRIME
7919 -> PRIME
10000 -> NOT PRIME
How is i * i <= n different from i <= Math.sqrt(n)?
| Feature | `i * i <= n` | `i <= Math.sqrt(n)` | |---|---|---| | Type | integer arithmetic | floating-point | | Rounding risk | none | sqrt can round, missing edge | | Overflow risk | yes, for large n | no | | Performance | fast integer multiply | slower sqrt per iteration |
For most values i * i <= n is preferred. For N near Integer.MAX_VALUE, use i <= n / i to avoid overflow.
// Overflow-safe bound for large n
for (int i = 3; i <= n / i; i += 2) {
if (n % i == 0) return false;
}
What are edge cases?
- 0 and 1 are not prime by definition.
- 2 is the smallest and only even prime.
- Negative numbers are not prime.
System.out.println(isPrime(0)); // false
System.out.println(isPrime(1)); // false
System.out.println(isPrime(2)); // true
System.out.println(isPrime(-7)); // false
What are common mistakes?
// Wrong: loop starts at 1 (1 divides everything)
for (int i = 1; i * i <= n; i++) {
if (n % i == 0) return false; // always returns false!
}
// Wrong: loop goes to n instead of sqrt(n)
for (int i = 2; i < n; i++) { // works but O(n), way too slow
if (n % i == 0) return false;
}
// Correct: starts at 2, stops at sqrt(n)
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) return false;
}
What about large primes and cryptography?
Trial division is fine for moderate numbers, but RSA keys use primes with hundreds of digits. For those, probabilistic tests like Miller-Rabin decide primality quickly with a negligible error chance. Java provides BigInteger.isProbablePrime(certainty) which runs Miller-Rabin internally.
import java.math.BigInteger;
BigInteger large = new BigInteger("104729");
System.out.println(large.isProbablePrime(20)); // true with high certainty
What should a senior engineer know?
A senior engineer knows that primality testing connects a simple loop to real financial security. The RSA keys that secure banking communications at National Bank of India depend on the difficulty of factoring the product of two large primes. Trial division checks small configuration parameters, but BigInteger.isProbablePrime handles cryptographic sizes.
For generating all primes up to N, the Sieve of Eratosthenes is far more efficient than testing each number individually.
What are common interview follow-up questions?
- How would you generate all primes up to N? (Sieve of Eratosthenes)
- What is the time complexity of trial division versus Miller-Rabin?
- Can you prove that divisors come in pairs below and above the square root?
Visual Overview
Input: n
│
▼
n < 2? ──Yes──→ return false
│ No
▼
n == 2? ──Yes──→ return true
│ No
▼
n % 2 == 0? ──Yes──→ return false
│ No
▼
i = 3
│
▼
┌──────────────────┐
│ i * i <= n? │──No──→ return true (prime)
│ │
│ Yes │
│ ▼ │
│ n % i == 0? │──Yes──→ return false (composite)
│ │ No │
│ ▼ │
│ i = i + 2 │
│ └─────────────┘
└──────────────────┘
Key Takeaway
A prime number is an integer greater than one whose only positive divisors are one and itself. The naive way to test primality is to try dividing by every number from two up to N minus one, but the key optimization is to stop at the square root of N. Divisors come in pairs that multiply to N, and in every pair one member is at most the square root, so if no divisor exists up to the square root there is none at all. That drops the work from linear to square-root time.
In code, handle the small cases first: numbers below two are not prime, two is the only even prime, and any other even number is immediately rejected. Then loop over odd divisors only, starting at three, which roughly halves the work. Write the loop bound as i * i <= n to avoid a floating-point square root, or i <= n / i for overflow safety near the integer limit.
In a banking project at National Bank of India, this validated special secure reference tokens that had to be prime for an indivisibility property. Because tokens were validated at high volume, the square-root optimization kept the issuing service fast. For a number like 7919, only about 44 checks were needed instead of nearly 8000.
The senior-level connection is to cryptography. Trial division handles moderate numbers, but the enormous primes in RSA key generation are far too large for it, so there probabilistic tests like Miller-Rabin decide primality quickly with negligible error. A humble loop that checks divisors up to a square root is the same idea that, scaled up with smarter algorithms, protects real financial transactions.
Remember one sentence: test divisors only up to the square root because divisors come in pairs, and one of each pair is always at or below the square root.
---