Strange Root


Strange Root

A number has a strange root if its square and square root share any digit. For example, 2 has a strange root because the square root of 2 equals 1.414 (consider the first three digits after the dot) and it contains 4 (which is the square of 2).

Examples:
Input: 11
Output: true 
(the square root of 11 is 3.317, the square of 11 is 121. They share the same digit, 1.)
 
Input: 24
Output: false (the square root of 24 (4.899) and square (576) do not share any digits) 

Write a program to check if the user input has a strange root or not.


Program

// set encoding of input stream
process.stdin.setEncoding('utf-8');

// Ask the user for input
console.log('Enter a number to check if its has strange roots. To quit enter : q');

// read user input
process.stdin.on('data', (data) => {
    if (data == 'q\n') {
        process.exit();
    }
    // if user has not entered any numbers value, notify
    if (isNaN(data)) {
        console.log('Please enter valid number only.');
        process.exit();
    }
    const num = parseInt(data);
    const square = Math.pow(num, 2).toString();
    const squareRoot = Math.sqrt(num).toFixed(3).toString(); // to fixed sets valid upto 3 decimal point 
    let flag = false; // to check if element contains in other string // constant variable cannot be reassigned

    // now check if any of the element of square is in square
    for (let index = 0; index < squareRoot.length; index++) {
        const element = squareRoot[index];
        if (square.indexOf(element) != -1) {
            flag = true;
        }
    }
    console.log(flag);
    process.exit();
})

Comments

Popular Posts