Basic Programming Concepts: Number Theory, Mathematical Computations, and Logic Building
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 whennumber
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
dividesnumber
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.
Nth Fibonacci Number
Given a non-negative integer n
, your task is to find the nth
Fibonacci number.
The Fibonacci sequence is defined as follows:
- F(0) = 0
- F(1) = 1
- F(n) = F(n - 1) + F(n - 2) for n > 1
function nthFibonacci(n) {
if (n === 0) return 0; // Base case for F(0)
if (n === 1) return 1; // Base case for F(1)
let a = 0, b = 1;
for (let i = 2; i <= n; i++) {
let next = a + b;
a = b;
b = next;
}
return b;
}
console.log(nthFibonacci(5));
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 tosum
.
Finding the Greatest Common Divisor (GCD) or (HCF) of Two Numbers
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).
Find the Missing Number in an Arithmetic Progression
Given an array in an arithmetic progression with one missing number, find the missing number.
function findMissingNumber(arr) {
let n = arr.length;
let diff = (arr[n-1] - arr[0]) / n;
for (let i = 0; i < n - 1; i++) {
if (arr[i+1] - arr[i] !== diff) {
return arr[i] + diff;
}
}
}
let arr = [2, 4, 8, 10, 12, 14];
console.log(findMissingNumber(arr)); // Output: 6
Program to Print Arithmetic Progression Series
function printAP(a, d, n) {
let result = [];
for (let i = 0; i < n; i++) {
result.push(a + i * d);
}
console.log(result.join(' '));
}
let a = 5, d = 2, n = 10;
printAP(a, d, n); // Output: 5 7 9 11 13 15 17 19 21 23
Check if Arithmetic Progression Can be Formed from Given Array
function canFormAP(arr) {
arr.sort((a, b) => a - b);
let diff = arr[1] - arr[0];
for (let i = 1; i < arr.length - 1; i++) {
if (arr[i+1] - arr[i] !== diff) {
return "No";
}
}
return "Yes";
}
let arr1 = [0, 12, 4, 8];
let arr2 = [12, 40, 11, 20];
console.log(canFormAP(arr1)); // Output: Yes
console.log(canFormAP(arr2)); // Output: No
Find the Opposite Face of a Dice
A standard dice has numbers from 1 to 6. Write a program to find the number on the opposite face of a given number.
function dice(n) {
switch (n) {
case 1:
console.log(6);
break;
case 2:
console.log(5);
break;
case 3:
console.log(4);
break;
case 4:
console.log(3);
break;
case 5:
console.log(2);
break;
default:
console.log(1);
break;
}
}
dice(2); // Output: 5
Explanation: The sum of the numbers on opposite faces of a dice is always 7. Based on this rule, the opposite face can be calculated.
Find Simple Interest
Write a program to calculate the simple interest using the formula:
function simpleInterest(principalAmount, rate, time) {
return (principalAmount * rate * time) / 100;
}
console.log(simpleInterest(10000, 5, 5)); // Output: 2500
Explanation: Simple interest is calculated by multiplying the principal amount, rate, and time, then dividing the result by 100.
Find Compound Interest
Write a program to calculate the compound interest using the formula:
function compoundInterest(principalAmount, rate, time) {
const amount = principalAmount * Math.pow((1 + rate / 100), time);
const CI = amount - principalAmount;
return CI;
}
console.log(compoundInterest(1000, 5, 2)); // Output: 102.5
console.log(compoundInterest(1500, 4.3, 6)); // Output: 438.836727
console.log(compoundInterest(2000, 3.5, 5)); // Output: 376.199437
Explanation: Compound interest is calculated by subtracting the principal amount from the total amount after compounding for a given time and rate.
Find the Area of a Circle
Write a program to calculate the area of a circle using the formula:
function findArea(radius) {
const area = Math.PI * radius * radius;
return area;
}
console.log(findArea(5)); // Output: 78.53981633974483
console.log(findArea(10)); // Output: 314.1592653589793
console.log(findArea(2.5)); // Output: 19.634954084936208
Explanation: The area of a circle is calculated using the mathematical constant ( \pi ) and the square of the radius.
Find the Number Closest to n and Divisible by m
Write a program to find the number closest to a given number n
that is divisible by m
.
function closestNum(n, m) {
let closest = Math.round(n / m);
return closest * m;
}
console.log(closestNum(-15, 6)); // Output: -18
console.log(closestNum(22, 7)); // Output: 21
Explanation: The closest number divisible by m
is calculated by dividing n
by m
, rounding the result to the nearest integer, and then multiplying back by m
.
Count Unique Pairs
Write a program to count the number of unique pairs that can be formed from N
players.
function countUniquePairs(N) {
if (N < 2) {
return 0; // No pairs possible with less than 2 players
}
return (N * (N - 1)) / 2; // Formula to calculate unique pairs
}
// Example usage
const N = 4;
console.log(`The number of unique pairs for ${N} players is:`, countUniquePairs(N));
Explanation: The number of unique pairs is calculated using the formula, which is derived from combinations.
Compute Sum of Multiples of 3, 5, or 7
Write a program to compute the sum of all positive integers less than n
that are multiples of 3, 5, or 7.
function computeMultipleSum(n) {
let sum = 0;
// Iterate through numbers less than n
for (let i = 1; i < n; i++) {
// Check if the number is a multiple of 3, 5, or 7
if (i % 3 === 0 || i % 5 === 0 || i % 7 === 0) {
sum += i; // Add to the sum
}
}
return sum; // Return the final sum
}
// Example usage
const n = 12;
console.log(`The sum of all positive multiples of 3, 5, or 7 below ${n} is:`, computeMultipleSum(n));
Explanation: The program iterates through all numbers less than n
and checks if each number is divisible by 3, 5, or 7. If true, the number is added to the sum.
Sum of the digits of a given number
Write a program to find the sum of the digits of a given number.
function sumOfDigits(n) {
let sum = 0;
while (n > 0) {
sum += n % 10;
n = Math.floor(n / 10);
}
return sum;
}
console.log(sumOfDigits(687)); // Output: 21
Explanation: This program iteratively extracts each digit of the number using the modulus operator, adds it to a running sum, and removes the last digit using integer division.
Find numbers from 1 to N with exactly 3 divisors
Write a program to find all numbers between 1 to N that have exactly 3 divisors.
function findNumbersWithThreeDivisors(N) {
let result = [];
for (let i = 2; i * i <= N; i++) {
if (isPrime(i)) {
result.push(i * i);
}
}
function isPrime(num) {
if (num <= 1) return false;
for (let j = 2; j * j <= num; j++) {
if (num % j === 0) return false;
}
return true;
}
return result;
}
console.log(findNumbersWithThreeDivisors(16)); // Output: [4, 9]
Explanation: Numbers with exactly three divisors are squares of prime numbers. The program first identifies prime numbers and then squares them if they are within the limit.
Check if a number is a power of another number
function isPower(x, y) {
if (y === 1) return true;
if (x === 0 || y === 0) return false;
while (y % x === 0) {
y /= x;
}
return y === 1;
}
console.log(isPower(10, 1)); // Output: true
Explanation: This program repeatedly divides y
by x
and checks if the remainder becomes 1, indicating that y
is a power of x
.
Square root of an integer
function integerSquareRoot(n) {
return Math.floor(Math.sqrt(n));
}
console.log(integerSquareRoot(4)); // Output: 2
Explanation: This program uses the built-in Math.sqrt
function to compute the square root of the number and rounds it down to the nearest integer using Math.floor
.
Print all Jumping Numbers smaller than or equal to a given value
Write a program to print all Jumping Numbers less than or equal to x
.
function jumpingNumbers(x) {
let result = [];
for (let i = 0; i <= x; i++) {
if (isJumping(i)) {
result.push(i);
}
}
function isJumping(num) {
let str = num.toString();
for (let j = 1; j < str.length; j++) {
if (Math.abs(str[j] - str[j - 1]) !== 1) {
return false;
}
}
return true;
}
return result;
}
console.log(jumpingNumbers(20)); // Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12]
Explanation: Jumping numbers are those where the difference between consecutive digits is 1. The program checks this condition for every number up to x
.
Program to add two fractions
function addFractions(n1, d1, n2, d2) {
let numerator = n1 * d2 + n2 * d1;
let denominator = d1 * d2;
let gcd = findGCD(numerator, denominator);
numerator /= gcd;
denominator /= gcd;
return `${numerator}/${denominator}`;
function findGCD(a, b) {
if (!b) return a;
return findGCD(b, a % b);
}
}
console.log(addFractions(1, 2, 3, 2)); // Output: 2/1
Explanation: The program calculates the sum of two fractions by finding a common denominator, adding the adjusted numerators, and simplifying the result using the GCD.
Fraction to Recurring Decimal
Write a program to convert a fraction to a recurring decimal if any.
function fractionToDecimal(a, b) {
let result = "";
let map = new Map();
let integerPart = Math.floor(a / b);
result += integerPart;
let remainder = a % b;
if (remainder === 0) return result;
result += ".";
while (remainder !== 0) {
if (map.has(remainder)) {
let idx = map.get(remainder);
result = result.slice(0, idx) + "(" + result.slice(idx) + ")";
break;
}
map.set(remainder, result.length);
remainder *= 10;
result += Math.floor(remainder / b);
remainder %= b;
}
return result;
}
console.log(fractionToDecimal(1, 2)); // Output: "0.5"
Explanation: The program uses a map to track remainders and identify when a repeating sequence starts. It constructs the decimal representation and encloses the recurring part in parentheses.
Program for sum of geometric series
Given the first term (a), common ratio (r), and number of terms (n), calculate the sum of the geometric series.
// Formula: S_n = a * (1 - r^n) / (1 - r) if r != 1
function geometricSeriesSum(a, r, n) {
if (r === 1) {
return a * n; // Special case when r is 1
}
return a * (1 - Math.pow(r, n)) / (1 - r);
}
// Example usage
const a = 2; // First term
const r = 3; // Common ratio
const n = 4; // Number of terms
console.log(`The sum of the geometric series is: ${geometricSeriesSum(a, r, n)}`);
Explanation: A geometric series is a sequence where each term is obtained by multiplying the previous term by a constant ratio (r). The formula calculates the sum based on whether the common ratio is 1 or not.