Data Structure and Algorithm
Math Coding Problem Street

Basic Programming Concepts: Number Theory and Mathematical Computations in JavaScript

Starting from scratch in coding, especially when tackling complex topics like Data Structures and Algorithms (DSA), can feel overwhelming. However, laying a strong foundation before diving into advanced concepts is essential. Building your problem-solving skills step by step will give you the confidence and understanding needed to tackle DSA with ease.

This journey is all about mastering problem-solving techniques and strengthening your technical foundation. By improving your skills, you’ll not only boost your confidence but also increase your chances of excelling in interviews and technical challenges at top tech companies. Take it one step at a time, stay focused, and you'll unlock the power of critical thinking—key to becoming an effective problem solver in the world of coding and tech.

Let’s get started and take your coding journey to the next level!

Determining Even or Odd Numbers

This program checks whether a number is even or odd.

function addEven(number) {
  if (number % 2 === 0) {
    return 'Even';
  } else {
    return 'Odd';
  }
}
console.log(addEven(10));

Explanation:

  • The % operator finds the remainder when number is divided by 2.
  • If the remainder is 0, the number is even; otherwise, it’s odd.

Shorter Version Using Ternary Operator

const number = 0;
console.log(number % 2 == 0 ? 'Even' : 'Odd');

Explanation:

  • The ternary operator provides a shorthand way to check conditions.

Swap Two Numbers

Using a Temporary Variable

a = 5, b = 10;
 
// Swap the numbers using a temporary variable
let temp = a;
a = b;
b = temp;
 
console.log("After swapping using a temporary variable:");
console.log("a =", a);
console.log("b =", b);

Swap Two Numbers Without Using a Third (Temporary) Variable


Using Addition and Subtraction

let a = 5, b = 10;
 
// Swap the numbers using addition and subtraction
a = a + b;
b = a - b;
a = a - b;
 
console.log("After swapping using addition and subtraction:");
console.log("a =", a);
console.log("b =", b);

Using XOR Bitwise Operator

a = 5, b = 10;
 
// Swap the numbers using XOR
a = a ^ b;
b = a ^ b;
a = a ^ b;
 
console.log("After swapping using XOR:");
console.log("a =", a);
console.log("b =", b);

Using Destructuring Assignment

a = 5, b = 10;
 
// Swap the numbers using destructuring
[a, b] = [b, a];
 
console.log("After swapping using destructuring:");
console.log("a =", a);
console.log("b =", b);

Using Multiplication and Division

a = 5, b = 10;
 
// Swap the numbers using multiplication and division
a = a * b;
b = a / b;
a = a / b;
 
console.log("After swapping using multiplication and division:");
console.log("a =", a);
console.log("b =", b);

Checking for Prime Numbers

This program checks if a number is a prime number. A prime number is a number greater than 1 that has no divisors other than 1 and itself. For example:

  • Prime numbers: 2, 3, 5, 7, 11, 13, etc.
  • Non-prime numbers: 1, 4, 6, 8, 9, 10, etc.
function primeNumber(number) {
  // If the input number is less than or equal to 1, it's not a prime number.
  if (number <= 1) {
    return false; // Return false as 0, 1, and negative numbers are not prime.
  }
 
  // Loop from 2 to (number - 1) to check for divisors.
  for (let i = 2; i < number; i++) {
    // If the number is divisible by any number between 2 and (number - 1),
    // it means it's not a prime number.
    if (number % i === 0) {
      return false; // Return false if a divisor is found.
    }
  }
 
  // If no divisors are found, the number is prime.
  return true;
}
 
// Test cases:
console.log(primeNumber(4));  // Output: false, because 4 is divisible by 2.
console.log(primeNumber(5));  // Output: true, because 5 is only divisible by 1 and 5.
console.log(primeNumber(1));  // Output: false, because 1 is not a prime number.
console.log(primeNumber(17)); // Output: true, because 17 is only divisible by 1 and 17.

Explanation:

  • A prime number is greater than 1 and divisible only by 1 and itself.
  • The loop checks if any number from 2 to number-1 divides number evenly.

Validating Leap Years

This program checks if a year is a leap year. A leap year occurs every 4 years, adding an extra day to February (29 days instead of 28).

function checkLeapYear(year) {
  // A year is a leap year if:
  // 1. It is divisible by 4 and NOT divisible by 100, OR
  // 2. It is divisible by 400
 
  if (
    (year % 4 === 0 && year % 100 !== 0) // Case 1: Divisible by 4 but not 100
    || 
    (year % 400 === 0) // Case 2: Divisible by 400
  ) {
    return 'Leap year'; // If either condition is true, it's a leap year
  } else {
    return 'Not a leap year'; // Otherwise, it's not a leap year
  }
}
 
// Example usage:
console.log(checkLeapYear(2022)); // Output: Not a leap year
console.log(checkLeapYear(2020)); // Output: Leap year
console.log(checkLeapYear(2000)); // Output: Leap year
console.log(checkLeapYear(1900)); // Output: Not a leap year

Explanation:

  • A leap year is divisible by 4 but not by 100, unless it is also divisible by 400.

Calculating Armstrong Numbers

An Armstrong number is one whose digits raised to the power of the number of digits sum up to the number itself.

function isArmstrongNumber(number) {
  // Step 1: Store the original number in a temporary variable for calculations.
  let temp = number;
 
  // Step 2: Initialize a variable to count the number of digits in the number.
  let digitsCount = 0;
 
  // Step 3: Calculate the number of digits in the number.
  while (temp > 0) {
    temp = Math.floor(temp / 10); // Remove the last digit from temp.
    digitsCount++; // Increment the digit count.
  }
 
  // Step 4: Reinitialize variables to calculate the Armstrong sum.
  let sum = 0; // Initialize the sum to store the sum of digits raised to the power of digitsCount.
  temp = number; // Reset temp to the original number for further processing.
 
  // Step 5: Calculate the Armstrong sum.
  while (temp > 0) {
    const digit = temp % 10; // Extract the last digit of temp.
    sum += Math.pow(digit, digitsCount); // Add the digit raised to the power of digitsCount to the sum.
    temp = Math.floor(temp / 10); // Remove the last digit from temp.
  }
 
  // Step 6: Compare the calculated sum with the original number.
  // If they are equal, it's an Armstrong Number; otherwise, it is not.
  return sum === number ? "Armstrong Number" : "Not an Armstrong Number";
}
 
// Example Usage:
console.log(isArmstrongNumber(153)); // Output: Armstrong Number

Explanation:

  • The program counts the digits and checks if the sum of the digits raised to their count equals the original number.

Other way implementation of the Armstrong number check

function checkArmstrongNumber(n){
    let armstrong = 0
    let temp = n
    while (temp > 0) {
        // get last one digit
        let remainder = temp%10
        armstrong += remainder * remainder * remainder
        temp = Math.floor(temp / 10)
    }
    return armstrong === n ? 'Amtrong' : 'Not amstrong'
}
const resultArmstrong = checkArmstrongNumber(153)
console.log(resultArmstrong)

Find Armstrong numbers between two numbers

function checkArmstrongNumber(n){
    let armstrong = 0
    let temp = n
    while (temp > 0) {
        // get last one digit
        let remainder = temp%10
        armstrong += remainder * remainder * remainder
        temp = Math.floor(temp / 10)
    }
    return armstrong === n ? 'Amtrong' : 'Not amstrong'
}
 
const a=0, z=153
// Find Armstrong numbers between a and z
for (let i = a; i <= z; i++) {
    if (checkArmstrongNumber(i) === 'Amtrong') {
        console.log(i)
    }
}

Generating the Fibonacci Series

This program generates Fibonacci numbers up to a given limit. The Fibonacci sequence is a list of numbers where each number is the sum of the two numbers that come before it. It starts with 0 and 1, and then every following number is the sum of the previous two. Here are the first few numbers in the Fibonacci sequence: 0,1,1,2,3,5,8,13,21,34,…

function generateFibonacciSeries(number) {
  if (number < 0) {
    return [];
  }
  const series = [];
  let a = 0, b = 1;
  while (a <= number) {
    series.push(a);
    let next = a + b;
    a = b;
    b = next;
  }
  return series;
}
console.log(generateFibonacciSeries(10));

The Fibonacci sequence is used in Computer Science for algorithms and data structures, in Mathematics for number theory and the Golden Ratio, in Financial Markets for technical analysis, in Art and Architecture for design and symmetry, and in Music for rhythm and composition.

Explanation:

  • The Fibonacci sequence starts with 0 and 1, and each number is the sum of the previous two.

Identifying Palindromes

This program checks if a number is a palindrome.

function isPalindromeNumber(number) {
  if (number < 0) {
    return "Not a Palindrome";
  }
 
  let reverse = 0;
  let temp = number;
  while (temp > 0) {
    let digit = temp % 10;
    reverse = reverse * 10 + digit;
    temp = Math.floor(temp / 10);
  }
  return number === reverse ? "Palindrome" : "Not a Palindrome";
}
console.log(isPalindromeNumber(121));

Explanation:

  • A palindrome reads the same forwards and backwards.

Summing Digits of a Number

This program adds all the digits of a number.

function sumDigitNumber(number) {
  let sum = 0;
  while (number > 0) {
    const digit = number % 10;
    sum += digit;
    number = Math.floor(number / 10);
  }
  return sum;
}
console.log(sumDigitNumber(1234));

Explanation:

  • The program extracts digits using % and adds them to sum.

Finding the Greatest Common Divisor (GCD)

This program finds the largest number that divides two numbers evenly.

function gcd(a, b) {
  if (b === 0) return a;
  return gcd(b, a % b);
}
console.log(gcd(48, 18));

Explanation:

  • The recursive approach uses the Euclidean algorithm to find GCD.

Finding the Least Common Multiple (LCM)

This program calculates the smallest number divisible by two numbers.

function lcm(a, b) {
  if (a === 0 || b === 0) return 0;
  return (Math.abs(a * b)) / gcd(a, b);
}
console.log(lcm(12, 15));

Explanation:

  • LCM is calculated using the formula: (a * b) / GCD.

Counting Vowels and Consonants in a String

This program counts the vowels and consonants in a string.

function countVowelsAndConsonants(str) {
  let vowelsCount = 0, consonantsCount = 0;
 
  for (let char of str) {
    const lowerChar = char.toLowerCase();
    if ("aeiou".includes(lowerChar)) {
      vowelsCount++;
    } else if (lowerChar >= 'a' && lowerChar <= 'z') {
      consonantsCount++;
    }
  }
 
  return { vowels: vowelsCount, consonants: consonantsCount };
}
console.log(countVowelsAndConsonants("Hello JS!"));

Explanation:

  • The program checks each character and categorizes it as a vowel or consonant.

Finding the Factorial of a Number

The factorial of a non-negative integer 𝑛 is the product of all positive integers less than or equal to 𝑛. It is denoted as 𝑛!. n!=n×(n−1)×(n−2)×⋯×1

Iterative Approach: This approach uses a for loop to compute the factorial.

function factorialIterative(n) {
  let result = 1;
  
  // If the number is 0 or 1, the factorial is 1
  if (n === 0 || n === 1) {
    return result;
  }
  
  // Calculate factorial using a loop
  for (let i = 2; i <= n; i++) {
    result *= i;
  }
  
  return result;
}
 
// Example Usage:
console.log(factorialIterative(5)); // Output: 120

Recursive Approach: This approach calls the function itself, reducing the problem size each time, until it reaches the base case.

function factorialRecursive(n) {
  // Base case: factorial of 0 or 1 is 1
  if (n === 0 || n === 1) {
    return 1;
  }
  
  // Recursive call
  return n * factorialRecursive(n - 1);
}
 
// Example Usage:
console.log(factorialRecursive(5)); // Output: 120

Finding All Divisors of a Number

To find all divisors of a given number, you can use an efficient method by iterating through numbers from 1 to the square root of the number. This reduces the time complexity.

function isDivisors(input) {
  if (input <= 0) {
    return {success: false, message: "Input should be a positive number"}; // Handling invalid input
  }
  
  const allDivisors = [];
  
  // Loop from 1 to input (inclusive) to find divisors
  for (let i = 1; i <= input; i++) {
    if (input % i === 0) {
      allDivisors.push(i);
    }
  }
  
  return allDivisors;
}
 
const resDivisors = isDivisors(10);
console.log(resDivisors); // Output: [1, 2, 5, 10]

Finding the Count of Specific Digits in a Number

If you want to count the occurrences of a specific digit in a number without converting the number to a string, you can achieve this by performing mathematical operations. Specifically, you can repeatedly extract digits from the number using division and modulus operations.

function countSpecificDigit(number, digit) {
  let count = 0;
  
  // Ensure the digit is between 0 and 9
  if (digit < 0 || digit > 9) {
    return "Digit must be between 0 and 9";
  }
 
  // Loop until the number becomes 0
  while (number > 0) {
    // Extract the last digit
    const lastDigit = number % 10;
 
    // Check if the last digit matches the target digit
    if (lastDigit === digit) {
      count++;
    }
 
    // Remove the last digit from the number
    number = Math.floor(number / 10);
  }
  
  return count;
}
 
// Example Usage:
const result = countSpecificDigit(122333, 3);
console.log(result); // Output: 3

Finding the Sum of Squares of Digits

To find the sum of the squares of the digits of a number, we can use a similar approach to counting digits by repeatedly extracting the last digit, squaring it, and adding it to the sum. Here's the solution:

function sumOfSquaresOfDigits(number) {
  let sum = 0;
 
  // Ensure the number is non-negative (handle negative inputs by making it positive)
  number = Math.abs(number);
 
  // Loop until the number becomes 0
  while (number > 0) {
    // Extract the last digit
    const lastDigit = number % 10;
 
    // Square the last digit and add to the sum
    sum += lastDigit * lastDigit;
 
    // Remove the last digit from the number
    number = Math.floor(number / 10);
  }
 
  return sum;
}
 
// Example Usage:
const result = sumOfSquaresOfDigits(123);
console.log(result); // Output: 14

Explanation: The sum of the squares of digits is 1^2 + 2^2 + 3^2 = 14.

Checking for Armstrong Numbers in a Range

To find all Armstrong numbers within a given range, we need to check each number in the range and see if it satisfies the Armstrong number condition. An Armstrong number is a number that is equal to the sum of its own digits raised to the power of the number of digits.

function findArmstrongNumbersInRange(range) {
  const [start, end] = range;
  const armstrongNumbers = [];
 
  // Loop through the range
  for (let num = start; num <= end; num++) {
    const numStr = num.toString();
    const numDigits = numStr.length;
    let sumOfPowers = 0;
 
    // Calculate the sum of digits raised to the power of numDigits
    for (let i = 0; i < numDigits; i++) {
      sumOfPowers += Math.pow(parseInt(numStr[i]), numDigits);
    }
 
    // Check if the sum is equal to the original number
    if (sumOfPowers === num) {
      armstrongNumbers.push(num);
    }
  }
 
  return armstrongNumbers;
}
 
// Example usage:
const result = findArmstrongNumbersInRange([1, 500]);
console.log(result); // Output: [1, 153, 370, 371, 407]

Generating Multiplication Tables

To generate the multiplication table for a given number, we need to iterate from 1 to a given limit (in this case, 5) and compute the product of the number with each integer in that range.

function generateMultiplicationTable(number, limit = 5) {
  const table = [];
  
  // Loop through numbers from 1 to the given limit
  for (let i = 1; i <= limit; i++) {
    // Calculate the product and push it into the table array
    table.push(`${number} x ${i} = ${number * i}`);
  }
  
  return table;
}
 
// Example Usage:
const result = generateMultiplicationTable(4);
console.log(result.join(", ")); // Output: 4 x 1 = 4, 4 x 2 = 8, 4 x 3 = 12, 4 x 4 = 16, 4 x 5 = 20

Finding Prime Numbers in a Range

To find all prime numbers within a given range, we need to iterate through the numbers in the range and check if each number is prime. A number is prime if it is greater than 1 and is only divisible by 1 and itself.

function isPrime(num) {
  if (num <= 1) return false; // 0 and 1 are not prime numbers
  for (let i = 2; i <= Math.sqrt(num); i++) {
    if (num % i === 0) return false; // Found a divisor, so not prime
  }
  return true; // Number is prime
}
 
function findPrimeNumbersInRange(range) {
  const [start, end] = range;
  const primeNumbers = [];
  
  // Loop through the range and check for prime numbers
  for (let num = start; num <= end; num++) {
    if (isPrime(num)) {
      primeNumbers.push(num);
    }
  }
 
  return primeNumbers;
}
 
// Example usage:
const result = findPrimeNumbersInRange([10, 30]);
console.log(result); // Output: [11, 13, 17, 19, 23, 29]

Checking for Perfect Numbers

A perfect number is a positive integer that is equal to the sum of its proper divisors (divisors excluding the number itself).

function isPerfectNumber(num) {
  if (num <= 1) return false; // Numbers less than or equal to 1 are not perfect numbers
 
  let sum = 0;
  // Loop through possible divisors from 1 to num/2
  for (let i = 1; i <= num / 2; i++) {
    if (num % i === 0) {
      sum += i; // Add divisor to sum
    }
  }
 
  return sum === num; // If the sum of divisors equals the number, it's a perfect number
}
 
// Example usage:
console.log(isPerfectNumber(6));  // Output: true (Perfect Number)
console.log(isPerfectNumber(496)); // Output: true (Perfect Number)

Calculating the Sum of Odd Numbers in a Range

To calculate the sum of all odd numbers within a given range, we need to identify the odd numbers and then sum them up.

function sumOfOddNumbersInRange(range) {
  const [start, end] = range;
  let sum = 0;
 
  // Loop through the range and check for odd numbers
  for (let num = start; num <= end; num++) {
    if (num % 2 !== 0) { // Check if the number is odd
      sum += num;
    }
  }
 
  return sum;
}
 
// Example usage:
const result = sumOfOddNumbersInRange([1, 10]);
console.log(result); // Output: 25

Explanation: The sum of odd numbers between 1 and 10 is 1 + 3 + 5 + 7 + 9 = 25.

Calculating the Sum of Odd Numbers in a Range

To calculate the sum of all odd numbers within a given range, we can iterate through the numbers in that range, check for odd numbers, and add them to the sum.

function sumOfOddNumbersInRange(range) {
  const [start, end] = range;
  let sum = 0;
 
  // Loop through the range and add odd numbers to the sum
  for (let num = start; num <= end; num++) {
    if (num % 2 !== 0) { // Check if the number is odd
      sum += num;
    }
  }
 
  return sum;
}
 
// Example usage:
const result = sumOfOddNumbersInRange([1, 10]);
console.log(result); // Output: 25

Explanation: The sum of odd numbers between 1 and 10 is 1 + 3 + 5 + 7 + 9 = 25.

Printing Prime Numbers Less Than a Given Number

To print all prime numbers less than a given number, we need to follow these steps:

function printPrimesLessThan(n) {
  // Function to check if a number is prime
  function isPrime(num) {
    if (num <= 1) return false; // Numbers less than or equal to 1 are not prime
    for (let i = 2; i <= Math.sqrt(num); i++) { // Check divisibility up to square root of num
      if (num % i === 0) return false; // If divisible, it's not prime
    }
    return true; // It's prime if no divisors were found
  }
 
  // Loop through numbers from 2 to n-1 and check if they are prime
  for (let num = 2; num < n; num++) {
    if (isPrime(num)) {
      console.log(num); // Print the prime number
    }
  }
}
 
// Example usage:
printPrimesLessThan(22);  // Output: 2, 3, 5, 7, 11, 13, 17, 19

Finding the Number of Digits in a Number

To find the number of digits in a given number, we can use a straightforward approach by converting the number to a string and checking its length. Alternatively, we can calculate it mathematically by repeatedly dividing the number by 10 until it becomes 0.

function countDigits(num) {
  let count = 0;
  while (num > 0) {
    num = Math.floor(num / 10); // Divide number by 10 and round down
    count++;
  }
  return count;
}
 
// Example usage:
const result = countDigits(12345);
console.log(result);  // Output: 5

Explanation: The number 12345 has 5 digits.

Checking if a Number is a Narcissistic Number

A Narcissistic Number (also known as an Armstrong number) is a number that is equal to the sum of its own digits each raised to the power of the number of digits.

function isNarcissisticNumber(num) {
  // Convert the number to a string to easily access each digit
  const digits = num.toString().split('');
  const numDigits = digits.length;
  
  // Calculate the sum of the digits raised to the power of the number of digits
  const sum = digits.reduce((acc, digit) => acc + Math.pow(Number(digit), numDigits), 0);
 
  // Check if the sum equals the original number
  if (sum === num) {
    return 'Narcissistic Number';
  } else {
    return 'Not a Narcissistic Number';
  }
}
 
// Example usage:
console.log(isNarcissisticNumber(153));  // Output: Narcissistic Number
console.log(isNarcissisticNumber(123));  // Output: Not a Narcissistic Number

Explanation: 153 is a narcissistic number because 1^3 + 5^3 + 3^3 = 153.

Finding the Sum of the Digits of the Factorial of a Number

To solve the problem of finding the sum of the digits of the factorial of a number, you can break it down into two main tasks:

function factorial(num) {
  let result = 1;
  for (let i = 1; i <= num; i++) {
    result *= i;
  }
  return result;
}
 
function sumOfDigitsOfFactorial(num) {
  // Step 1: Calculate the factorial
  const fact = factorial(num);
  
  // Step 2: Convert the factorial to a string and sum its digits
  const sum = fact.toString().split('').reduce((acc, digit) => acc + Number(digit), 0);
  
  return sum;
}
 
// Example usage:
console.log(sumOfDigitsOfFactorial(4));  // Output: 6 (factorial of 4 is 24, and sum of digits is 2 + 4 = 6)

Calculating the Power of a Number

To calculate the power of a number (i.e., base raised to the exponent), you can use the following formula: 2^3 =2×2×2=8

Using Math.pow():

function power(base, exponent) {
  // Step 1: Calculate the power of the base raised to the exponent
  return Math.pow(base, exponent);
}
 
// Example usage:
console.log(power(2, 3));  // Output: 8

Alternative Approach Without Using Math.pow():

function power(base, exponent) {
  let result = 1;
  
  // Multiply the base by itself 'exponent' times
  for (let i = 1; i <= exponent; i++) {
    result *= base;
  }
  
  return result;
}
 
// Example usage:
console.log(power(2, 3));  // Output: 8

Finding the N-th Triangular Number

function triangularNumber(N) {
  // Using the formula to calculate the N-th triangular number
  return (N * (N + 1)) / 2;
}
 
// Example usage:
console.log(triangularNumber(4));  // Output: 10

Explanation: The 4th triangular number is 10 (sum of the first 4 natural numbers).

Checking for Perfect Squares

A perfect square is a number that can be expressed as the square of an integer. For example, 16 is a perfect square because 4×4=16.

function isPerfectSquare(number) {
  // Find the square root of the number
  let sqrt = Math.sqrt(number);
 
  // Check if the square root is an integer
  return sqrt === Math.floor(sqrt);
}
 
// Example usage:
console.log(isPerfectSquare(16));  // Output: true
console.log(isPerfectSquare(18));  // Output: false

Explanation: 16 is a perfect square (4^2 = 16).