CodeMIRAI
0 XP

Classic number programs

3 min read 10 runnable examples Quiz included

These short programs come up again and again in classes, tests and interviews. Each one is a small puzzle built from the loops and conditions you already know. Read the idea, run the code, then change the number and run it again.

Even or odd

A number is even when dividing it by 2 leaves no remainder:

JavaScript
for (const n of [7, 12, 0, -3]) {
  console.log(n, n % 2 === 0 ? "is even" : "is odd");
}

-3 % 2 is -1 in JavaScript, not 1, which is why the test is === 0 and not === 1.

Leap year

A year is a leap year if it divides by 4, except century years, which must also divide by 400:

JavaScript
function isLeap(year) {
  return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
}
for (const y of [2024, 2026, 1900, 2000]) {
  console.log(y, isLeap(y) ? "is a leap year" : "is not a leap year");
}

Prime numbers

A prime number has exactly two divisors: 1 and itself (2, 3, 5, 7, 11...). To test n, try dividing it by every number from 2 upwards. You only need to go up to the square root of n: if n had a factor bigger than that, it would also have a smaller one you'd already have found.

JavaScript
function isPrime(n) {
  if (n < 2) return false;
  for (let d = 2; d * d <= n; d++) {
    if (n % d === 0) return false;   // found a divisor: not prime
  }
  return true;
}
console.log(isPrime(29), isPrime(91), isPrime(2), isPrime(1));

All the primes up to 50, using the function in a loop:

JavaScript
function isPrime(n) {
  if (n < 2) return false;
  for (let d = 2; d * d <= n; d++) {
    if (n % d === 0) return false;
  }
  return true;
}
const primes = [];
for (let n = 2; n <= 50; n++) {
  if (isPrime(n)) primes.push(n);
}
console.log(primes.join(" "));
console.log(primes.length, "primes");

The Fibonacci series

Each number is the sum of the two before it: 0, 1, 1, 2, 3, 5, 8, ... Keep the last two numbers in variables and slide them along:

JavaScript
let a = 0;
let b = 1;
const series = [];
for (let i = 1; i <= 10; i++) {
  series.push(a);
  const next = a + b;
  a = b;
  b = next;
}
console.log(series.join(", "));

Palindrome numbers

A palindrome reads the same both ways, like 12321. Reverse the digits (from the loop patterns lesson) and compare:

JavaScript
function isPalindrome(n) {
  let original = n;
  let reversed = 0;
  while (n > 0) {
    reversed = reversed * 10 + (n % 10);
    n = Math.floor(n / 10);
  }
  return reversed === original;
}
for (const n of [121, 12321, 123, 7]) {
  console.log(n, isPalindrome(n) ? "is a palindrome" : "is not a palindrome");
}

For words, compare the string with its reverse: word === [...word].reverse().join("").

Armstrong numbers

An Armstrong number equals the sum of its digits, each raised to the power of the number of digits. 153 has 3 digits, and 1³ + 5³ + 3³ = 1 + 125 + 27 = 153:

JavaScript
function isArmstrong(n) {
  const digits = String(n).length;
  let sum = 0;
  let rest = n;
  while (rest > 0) {
    sum += (rest % 10) ** digits;
    rest = Math.floor(rest / 10);
  }
  return sum === n;
}
const found = [];
for (let n = 1; n <= 1000; n++) {
  if (isArmstrong(n)) found.push(n);
}
console.log(found.join(" "));

GCD and LCM

The GCD (greatest common divisor, also called HCF) of two numbers is the biggest number that divides both. Euclid's method keeps replacing the pair with (the smaller number, the remainder) until the remainder is 0:

JavaScript
function gcd(a, b) {
  while (b !== 0) {
    const r = a % b;
    a = b;
    b = r;
  }
  return a;
}
const x = 48;
const y = 36;
console.log(`GCD of ${x} and ${y} is ${gcd(x, y)}`);
console.log(`LCM of ${x} and ${y} is ${(x * y) / gcd(x, y)}`);
aba % b
483612
36120
120stop: the GCD is 12

The LCM (lowest common multiple) is then a × b ÷ GCD.

Swapping two values

The classic way uses a temporary variable; modern JavaScript can swap with destructuring:

JavaScript
let a = 5;
let b = 9;
const temp = a;
a = b;
b = temp;
console.log("after the swap:", a, b);

[a, b] = [b, a];   // swap back, in one line
console.log("swapped again:", a, b);

Your turn

Pick a number in the Input box; the program tells you everything this lesson can about it:

JavaScript
const n = Number(prompt("Pick a whole number"));
let isPrime = n >= 2;
for (let d = 2; d * d <= n; d++) {
  if (n % d === 0) isPrime = false;
}
let rest = n;
let reversed = 0;
let digitSum = 0;
while (rest > 0) {
  reversed = reversed * 10 + (rest % 10);
  digitSum += rest % 10;
  rest = Math.floor(rest / 10);
}
console.log(`${n} is ${n % 2 === 0 ? "even" : "odd"}`);
console.log(`prime: ${isPrime}`);
console.log(`digit sum: ${digitSum}, reversed: ${reversed}`);
console.log(`palindrome: ${reversed === n}`);
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.