Skip to content

Latest commit

 

History

History
99 lines (75 loc) · 1.88 KB

25-07-23.md

File metadata and controls

99 lines (75 loc) · 1.88 KB

Practice problems

Check whether a number (from 1 to 100) is prime or not

const primes = [2, 3, 5, 7];

function isPrime(num) {
    const nearestPerfectSq = Math.floor(Math.sqrt(num));

    for(let i of primes) {
        let isDivisible = (num % i === 0);

        if(i<=nearestPerfectSq && isDivisible) return false;
    }

    return true;
}

let nums = Array(99).fill(0).map((_, i)=>i+2);
for(let num of nums ) {
    let is = isPrime(num);
    is && console.log(`${num} is prime`);
}

Check whether a number is Armstrong number or not

function isArmstrong(num) {
    let numStr = `${num}`
    let d1 = +numStr[0];
    let d2 = +numStr[1];
    let d3 = +numStr[2];

    return num === (d1**3 + d2**3 + d3**3);
}

let nums = Array(900).fill(0).map((_, i)=>i+100);

for(let num of nums ) {
    let is = isArmstrong(num);
    is && console.log(`${num} is armstrong.`);
}

// 153 is armstrong.
// 370 is armstrong.
// 371 is armstrong.
// 407 is armstrong.

define a function to make pyramid pattern

function generatePyramid(num) {
    let maxCols = 2*num -1;
    let mid = Math.floor(maxCols / 2);
    let rows = [];

    for(let i = 1; i <= num; i++) {
        let row = Array(maxCols).fill(" ");
        
        for(let j = 0; j < i; j++){
            row[mid+j] = "*";
            row[mid-j] = "*";
        }
        row = row.join("");
        rows.push(row)
    }
    return rows.join("\n");
}

console.log(generatePyramid(4));

//     *    
//    ***   
//   *****  
//  ******* 

Fetch data from https://jsonplaceholder.typicode.com/users by using async await

async function fetchUsers() {
    const res = await fetch("https://jsonplaceholder.typicode.com/users");

    const users = await res.json();

    return users;
}

fetchUsers()
    .then( users=> {
        console.log(users[0]);
    })
    .catch(err => {
        console.log(err.message);
    });