Must-Know Programs for Campus Recruitments: Part 2

Must-Know Programs for Campus Recruitments: Part 2

  1. Write a program to print prime number in a given range

     // Function to check if a number is prime
     const isPrime = num => {
         // 1 and numbers less than 1 are not prime
         if (num <= 1) {
             return false;
         }
         // 2 and 3 are prime numbers
         if (num <= 3) {
             return true;
         }
         // Numbers divisible by 2 or 3 are not prime
         if (num % 2 === 0 || num % 3 === 0) {
             return false;
         }
         // Check all numbers of the form 6k ± 1 up to √num
         for (let i = 5; i * i <= num; i += 6) {
             if (num % i === 0 || num % (i + 2) === 0) {
                 return false;
             }
         }
         return true;
     };
    
     // Function to print prime numbers in a given range
     const printPrimesInRange = (start, end) => {
         if (start > end || start < 0 || end < 0) {
             console.log("Invalid range.");
             return;
         }
    
         for (let number = start; number <= end; number++) {
             if (isPrime(number)) {
                 console.log(number);
             }
         }
     };
    
     // Example usage:
     const startRange = 10;
     const endRange = 50;
     console.log(`Prime numbers between ${startRange} and ${endRange}:`);
     printPrimesInRange(startRange, endRange);
    
  2. Write a program to print Armstrong numbers between two intervals

     // Function to check if a number is an Armstrong number
     const isArmstrong = num => {
         const numStr = String(num);
         const len = numStr.length;
         let sum = 0;
    
         for (let digit of numStr) {
             sum += Math.pow(parseInt(digit), len);
         }
    
         return sum === num;
     };
    
     // Function to print Armstrong numbers between two intervals
     const printArmstrongNumbers = (start, end) => {
         if (start > end || start < 0 || end < 0) {
             console.log("Invalid range.");
             return;
         }
    
         console.log(`Armstrong numbers between ${start} and ${end}:`);
         for (let number = start; number <= end; number++) {
             if (isArmstrong(number)) {
                 console.log(number);
             }
         }
     };
    
     // Example usage:
     const startInterval = 100;
     const endInterval = 1000;
     printArmstrongNumbers(startInterval, endInterval);
    
  3. Write a program to express a number as a sum of two prime numbers

     // Function to check if a number is prime
     const isPrime = num => {
         if (num <= 1) return false; // 1 and numbers less than 1 are not prime
         if (num <= 3) return true; // 2 and 3 are prime numbers
         if (num % 2 === 0 || num % 3 === 0) return false; // Numbers divisible by 2 or 3 are not prime
    
         // Check all numbers of the form 6k ± 1 up to √num
         for (let i = 5; i * i <= num; i += 6) {
             if (num % i === 0 || num % (i + 2) === 0) {
                 return false;
             }
         }
         return true;
     };
    
     // Function to find and print two prime numbers whose sum is equal to the given number
     const expressAsSumOfTwoPrimes = num => {
         if (num <= 2) {
             console.log("Number should be greater than 2.");
             return;
         }
    
         let prime1 = 0, prime2 = 0;
    
         // Check for prime pairs (prime1, prime2) such that prime1 + prime2 = num
         for (let i = 2; i <= num / 2; i++) {
             if (isPrime(i) && isPrime(num - i)) {
                 prime1 = i;
                 prime2 = num - i;
                 break;
             }
         }
    
         if (prime1 !== 0 && prime2 !== 0) {
             console.log(`${num} can be expressed as the sum of ${prime1} and ${prime2}`);
         } else {
             console.log(`No two prime numbers found whose sum is equal to ${num}`);
         }
     };
    
     // Example usage:
     const numberToExpress = 34;
     expressAsSumOfTwoPrimes(numberToExpress);
    
  4. Write a program to Replace all 0's with 1 in a given integer

     const replaceZerosWithOnes = num => {
         // Convert number to string
         let numStr = num.toString();
    
         // Replace all '0's with '1's
         numStr = numStr.replace(/0/g, '1');
    
         // Convert back to integer
         const result = parseInt(numStr, 10);
    
         return result;
     };
    
     // Example usage:
     const number = 102030;
     const replacedNumber = replaceZerosWithOnes(number);
     console.log(`Original number: ${number}`);
     console.log(`Number with all 0's replaced by 1's: ${replacedNumber}`);
    
  5. Write a program to print Pyramid pattern using stars

     const printPyramid = height => {
         // Iterate through each row (from 1 to height)
         for (let i = 1; i <= height; i++) {
             // Add spaces for alignment
             let row = ' '.repeat(height - i);
             // Add stars
             row += '*'.repeat(2 * i - 1);
             // Print the row
             console.log(row);
         }
     };
    
     // Example usage:
     const pyramidHeight = 5;
     console.log(`Pyramid pattern with height ${pyramidHeight}:`);
     printPyramid(pyramidHeight);
    
  6. Write a program to print Pyramid pattern using numbers

     const printNumberPyramid = height => {
         // Iterate through each row (from 1 to height)
         for (let i = 1; i <= height; i++) {
             // Add spaces for alignment
             let row = ' '.repeat(height - i);
    
             // Add numbers in ascending order
             for (let j = 1; j <= i; j++) {
                 row += j + ' ';
             }
    
             // Remove the extra space at the end of the row
             row = row.trim();
    
             // Print the row
             console.log(row);
         }
     };
    
     // Example usage:
     const pyramidHeight = 5;
     console.log(`Number Pyramid pattern with height ${pyramidHeight}:`);
     printNumberPyramid(pyramidHeight);
    
  7. Write a program to print Palindromic pyramid pattern printing

     const printPalindromicPyramid = height => {
         // Iterate through each row (from 1 to height)
         for (let i = 1; i <= height; i++) {
             // Create an empty string to store the current row
             let row = '';
    
             // Build the first half of the row (numbers)
             for (let j = 1; j <= i; j++) {
                 row += j + ' ';
             }
    
             // Build the second half of the row (numbers in reverse order)
             for (let k = i - 1; k >= 1; k--) {
                 row += k + ' ';
             }
    
             // Remove the extra space at the end of the row
             row = row.trim();
    
             // Add spaces for alignment
             let spaces = ' '.repeat(height - i);
    
             // Print the row with alignment
             console.log(spaces + row);
         }
     };
    
     // Example usage:
     const pyramidHeight = 5;
     console.log(`Palindromic Pyramid pattern with height ${pyramidHeight}:`);
     printPalindromicPyramid(pyramidHeight);
    
  8. Write a program to calculate maximum number of handshakes

     // Function to calculate the maximum number of handshakes
     const maxHandshakes = numPeople => {
         // Calculate the number of combinations of 2 people out of numPeople
         const maxHandshakesCount = numPeople * (numPeople - 1) / 2;
         return maxHandshakesCount;
     };
    
     // Example usage:
     const numberOfPeople = 5;
     const totalHandshakes = maxHandshakes(numberOfPeople);
     console.log(`Maximum number of handshakes with ${numberOfPeople} people: ${totalHandshakes}`);
    
  9. Write a program to find the Quadrants in which coordinates lie

     const findQuadrant = (x, y) => {
         if (x > 0 && y > 0) {
             return "Quadrant I";
         } else if (x < 0 && y > 0) {
             return "Quadrant II";
         } else if (x < 0 && y < 0) {
             return "Quadrant III";
         } else if (x > 0 && y < 0) {
             return "Quadrant IV";
         } else if (x === 0 && y !== 0) {
             return "On the Y-axis";
         } else if (y === 0 && x !== 0) {
             return "On the X-axis";
         } else {
             return "At the origin (0, 0)";
         }
     };
    
     // Example usage:
     const coordinates = [
         { x: 5, y: 7 },
         { x: -3, y: 2 },
         { x: -4, y: -2 },
         { x: 3, y: -5 },
         { x: 0, y: 0 },
         { x: 0, y: 5 },
         { x: -7, y: 0 }
     ];
    
     coordinates.forEach(coord => {
         const quadrant = findQuadrant(coord.x, coord.y);
         console.log(`(${coord.x}, ${coord.y}) lies ${quadrant}`);
     });
    
  10. Write a program to convert digit/number to words

    const ones = ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];
    const teens = ['ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'];
    const tens = ['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'];
    
    const convertNumberToWords = num => {
        if (num === 0) {
            return 'zero';
        }
    
        let words = '';
    
        // Handling hundreds place
        if (num >= 100) {
            words += ones[Math.floor(num / 100)] + ' hundred ';
            num %= 100;
        }
    
        // Handling tens and ones place
        if (num >= 20) {
            words += tens[Math.floor(num / 10)] + ' ';
            num %= 10;
        } else if (num >= 10) {
            words += teens[num - 10];
            num = 0; // no need to proceed further
        }
    
        if (num > 0) {
            words += ones[num];
        }
    
        return words.trim();
    };
    
    // Example usage:
    const number = 573;
    const words = convertNumberToWords(number);
    console.log(`${number} in words: ${words}`);
    
  11. Write a program to find Number of days in a given month of a given year

    const daysInMonth = (month, year) => {
        // Validate month and year
        if (month < 1 || month > 12) {
            return 'Invalid month';
        }
    
        // Handle February based on leap year
        if (month === 2) {
            if ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0) {
                return 29; // Leap year, February has 29 days
            } else {
                return 28; // Not a leap year, February has 28 days
            }
        }
    
        // Handle months with 30 days
        if ([4, 6, 9, 11].includes(month)) {
            return 30;
        }
    
        // All other months have 31 days
        return 31;
    };
    
    // Example usage:
    const month = 2; // February
    const year = 2024; // Leap year
    const numDays = daysInMonth(month, year);
    console.log(`Number of days in ${month}/${year}: ${numDays}`);
    
  12. Write a program to find Permutation in which n people can occupy r seats in a classroom

    // Function to calculate factorial
    const factorial = num => {
        if (num === 0 || num === 1) {
            return 1;
        }
        return num * factorial(num - 1);
    };
    
    // Function to calculate permutations
    const permutations = (n, r) => {
        if (n < r || n <= 0 || r <= 0) {
            return 'Invalid input: n must be greater than or equal to r, and both must be positive integers.';
        }
    
        const permutationCount = factorial(n) / factorial(n - r);
        return permutationCount;
    };
    
    // Example usage:
    const n = 8; // Number of people
    const r = 4; // Number of seats
    const numPermutations = permutations(n, r);
    console.log(`Number of permutations of ${n} people occupying ${r} seats: ${numPermutations}`);
    
  13. Write a program for Binary to decimal conversion

    const binaryToDecimal = binary => {
        // Convert binary string to integer using parseInt
        const decimal = parseInt(binary, 2);
        return decimal;
    };
    
    // Example usage:
    const binaryNumber = '101010';
    const decimalNumber = binaryToDecimal(binaryNumber);
    console.log(`Binary number ${binaryNumber} is equivalent to decimal number ${decimalNumber}`);
    
  14. Write a program for Decimal to binary conversion

    const decimalToBinary = decimal => {
        // Handle edge case for zero
        if (decimal === 0) {
            return '0';
        }
    
        let binary = '';
        let num = decimal;
    
        while (num > 0) {
            // Get the remainder when dividing by 2
            binary = (num % 2) + binary;
            // Integer division by 2
            num = Math.floor(num / 2);
        }
    
        return binary;
    };
    
    // Example usage:
    const decimalNumber = 42;
    const binaryNumber = decimalToBinary(decimalNumber);
    console.log(`Decimal number ${decimalNumber} is equivalent to binary number ${binaryNumber}`);
    
  15. Write a program for Binary to octal conversion

    // Function to convert binary to octal
    const binaryToOctal = binary => {
        // Convert binary to decimal first
        const decimal = parseInt(binary, 2);
    
        // Convert decimal to octal
        const octal = decimal.toString(8);
    
        return octal;
    };
    
    // Example usage:
    const binaryNumber = '101010';
    const octalNumber = binaryToOctal(binaryNumber);
    console.log(`Binary number ${binaryNumber} is equivalent to octal number ${octalNumber}`);
    
  16. Write a program for Octal to binary conversion

    // Function to convert octal to binary
    const octalToBinary = octal => {
        let binary = '';
    
        // Loop through each octal digit
        for (let i = 0; i < octal.length; i++) {
            const octalDigit = Number(octal[i]); // Convert octal digit to number
    
            // Convert octal digit to 3-digit binary representation
            let binaryDigit = octalDigit.toString(2);
    
            // Pad the binary representation to ensure it's 3 digits
            if (i > 0) {
                binaryDigit = binaryDigit.padStart(3, '0');
            }
    
            // Append the binary representation to the result
            binary += binaryDigit;
        }
    
        return binary;
    };
    
    // Example usage:
    const octalNumber = '52';
    const binaryNumber = octalToBinary(octalNumber);
    console.log(`Octal number ${octalNumber} is equivalent to binary number ${binaryNumber}`);
    
  17. Write a program to find number of integers which has exactly 9 divisors

    // Function to count divisors
    const countDivisors = n => {
        let divisorCount = 0;
        const sqrtN = Math.sqrt(n);
    
        for (let i = 1; i <= sqrtN; i++) {
            if (n % i === 0) {
                if (n / i === i) {
                    // i is a perfect square divisor
                    divisorCount++;
                } else {
                    // i and n/i are divisors
                    divisorCount += 2;
                }
            }
        }
    
        return divisorCount;
    };
    
    // Function to find numbers with exactly 9 divisors
    const countIntegersWith9Divisors = limit => {
        let count = 0;
    
        // Check for numbers of the form p^8
        for (let p = 2; p * p * p * p * p * p * p * p <= limit; p++) {
            const n1 = p ** 8;
            if (countDivisors(n1) === 9) {
                count++;
            }
        }
    
        // Check for numbers of the form p^2 * q where p and q are distinct primes
        for (let p = 2; p * p <= limit; p++) {
            for (let q = p + 1; p * p * q <= limit; q++) {
                const n2 = p ** 2 * q;
                if (countDivisors(n2) === 9) {
                    count++;
                }
            }
        }
    
        return count;
    };
    
    // Example usage:
    const upperLimit = 1000000; // Adjust the limit as needed
    const integersWith9Divisors = countIntegersWith9Divisors(upperLimit);
    console.log(`Number of integers with exactly 9 divisors up to ${upperLimit}: ${integersWith9Divisors}`);
    
  18. Write a program to print Solid and hollow rectangle star pattern

    const printSolidRectangle = (rows, cols) => {
        for (let i = 1; i <= rows; i++) {
            let row = '';
            for (let j = 1; j <= cols; j++) {
                row += '* ';
            }
            console.log(row);
        }
    };
    
    // Example usage:
    const solidRows = 5;
    const solidCols = 7;
    console.log(`Solid Rectangle Pattern (${solidRows} rows x ${solidCols} columns):`);
    printSolidRectangle(solidRows, solidCols);
    
    const printHollowRectangle = (rows, cols) => {
        for (let i = 1; i <= rows; i++) {
            let row = '';
            for (let j = 1; j <= cols; j++) {
                if (i === 1 || i === rows || j === 1 || j === cols) {
                    row += '* ';
                } else {
                    row += '  '; // Two spaces to maintain rectangular shape
                }
            }
            console.log(row);
        }
    };
    
    // Example usage:
    const hollowRows = 5;
    const hollowCols = 7;
    console.log(`Hollow Rectangle Pattern (${hollowRows} rows x ${hollowCols} columns):`);
    printHollowRectangle(hollowRows, hollowCols);
    
  19. Write a program to print Diamond pattern printing using stars

    const printDiamond = n => {
        if (n % 2 === 0) {
            console.log('Please provide an odd number to print a diamond pattern.');
            return;
        }
    
        // Upper part of the diamond
        for (let i = 0; i < n; i++) {
            let row = '';
            const spaces = Math.abs(Math.floor(n / 2) - i);
            const stars = n - 2 * spaces;
    
            // Add leading spaces
            for (let j = 0; j < spaces; j++) {
                row += ' ';
            }
    
            // Add stars
            for (let j = 0; j < stars; j++) {
                row += '*';
            }
    
            console.log(row);
        }
    
        // Lower part of the diamond (excluding the middle row)
        for (let i = n - 2; i >= 0; i--) {
            let row = '';
            const spaces = Math.abs(Math.floor(n / 2) - i);
            const stars = n - 2 * spaces;
    
            // Add leading spaces
            for (let j = 0; j < spaces; j++) {
                row += ' ';
            }
    
            // Add stars
            for (let j = 0; j < stars; j++) {
                row += '*';
            }
    
            console.log(row);
        }
    };
    
    // Example usage:
    const diamondSize = 7;
    console.log(`Diamond Pattern of size ${diamondSize}:`);
    printDiamond(diamondSize);
    
  20. Write a program to print Diamond pattern printing using numbers

    const printDiamondNumbers = n => {
        if (n % 2 === 0) {
            console.log('Please provide an odd number to print a diamond pattern.');
            return;
        }
    
        // Upper part of the diamond
        let num = 1;
        for (let i = 0; i < n; i++) {
            let row = '';
            const spaces = Math.abs(Math.floor(n / 2) - i);
            const numbers = n - 2 * spaces;
    
            // Add leading spaces
            for (let j = 0; j < spaces; j++) {
                row += ' ';
            }
    
            // Add numbers
            for (let j = 0; j < numbers; j++) {
                row += num;
                num = num < 9 ? num + 1 : 1; // Reset to 1 after 9
            }
    
            console.log(row);
        }
    
        // Lower part of the diamond (excluding the middle row)
        num = 1; // Reset num for lower part
        for (let i = n - 2; i >= 0; i--) {
            let row = '';
            const spaces = Math.abs(Math.floor(n / 2) - i);
            const numbers = n - 2 * spaces;
    
            // Add leading spaces
            for (let j = 0; j < spaces; j++) {
                row += ' ';
            }
    
            // Add numbers
            for (let j = 0; j < numbers; j++) {
                row += num;
                num = num < 9 ? num + 1 : 1; // Reset to 1 after 9
            }
    
            console.log(row);
        }
    };
    
    // Example usage:
    const diamondSize = 7;
    console.log(`Diamond Pattern of size ${diamondSize}:`);
    printDiamondNumbers(diamondSize);
    
  21. Write a program to print Floyd's triangle

    const printFloydsTriangle = rows => {
        let number = 1;
        for (let i = 1; i <= rows; i++) {
            let row = '';
            for (let j = 1; j <= i; j++) {
                row += number + ' ';
                number++;
            }
            console.log(row);
        }
    };
    
    // Example usage:
    const triangleRows = 5;
    console.log(`Floyd's Triangle with ${triangleRows} rows:`);
    printFloydsTriangle(triangleRows);
    
  22. Write a program to print Pascal triangle

    const printPascalsTriangle = numRows => {
        // Initialize the triangle with the first row
        let triangle = [[1]];
    
        // Generate subsequent rows of the triangle
        for (let i = 1; i < numRows; i++) {
            // Create a new row array
            const row = [];
            // First element of the row is always 1
            row.push(1);
            // Fill the row with the elements calculated based on the previous row
            for (let j = 1; j < i; j++) {
                row.push(triangle[i - 1][j - 1] + triangle[i - 1][j]);
            }
            // Last element of the row is always 1
            row.push(1);
            // Push the row to the triangle
            triangle.push(row);
        }
    
        // Print the triangle
        for (let i = 0; i < triangle.length; i++) {
            console.log(' '.repeat(numRows - i - 1) + triangle[i].join(' '));
        }
    };
    
    // Example usage:
    const pascalsTriangleRows = 5;
    console.log(`Pascal's Triangle with ${pascalsTriangleRows} rows:`);
    printPascalsTriangle(pascalsTriangleRows);