Open In App

JavaScript Program to Multiply the Given Number by 2 such that it is Divisible by 10

Last Updated : 03 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to implement a program through which we can find the minimum number of operations needed to make a number divisible by 10. We have to multiply it by 2 so that the resulting number will be divisible by 10. Our task is to calculate the minimum number of operations needed to make the number divisible by 10. If it is not possible to convert, then print -1.

Examples:

Input: 10 
Output: 0 
As the given number is itself divisible by 10, 
the answer is 0.

Input: 1 
Output: -1 
As by multiplying with 2, given no. can’t be 
converted into a number that is divisible by 10, 
therefore the answer is -1.

Using If Else Statement

The below code uses an if block to check first if the number is divisible by 10 or not. If it is not, then it will enter the if loop and multiply the number by 2. It then enters another if loop to check if the multiplied number is divisible by 10 or not by checking its last digit. The count variable keeps track of the number of operations performed. Inside the next if-else, it checks if the given number is divisible by 10, prints the count, i.e., the minimum number of operations, and else prints -1.

Syntax

if (condition) {
} 
else {
}

Example: This example shows the use of the above-explained apporach.

Javascript




const checkDivisibleBy2 = (inputNumber) => {
    let count = 0;
    if (inputNumber < 0) {
        return -1;
    }
    if (inputNumber % 10 !== 0) {
        inputNumber *= 2;
        if (inputNumber % 10 == 0 ||
            inputNumber % 10 == 5) 
        {
            count++;
        }
    }
    if (inputNumber % 10 === 0)
        return count;
    else return -1;
};
let testCase = -210;
console.log(checkDivisibleBy2(testCase));


Output

-1

Using While Loop

This approach minimizes the number of unnecessary iterations. It first checks if n is divisible by 5. If it is, then it enters the loop to double it until it becomes divisible by 10, while counting the number of times it doubles. If n is not divisible by 5 but is divisible by 10, then it outputs the count. If neither of the conditions is met, then it outputs -1.

Syntax

while (condition) {}

Example: This example shows the use of the above-explained apporach.

Javascript




const checkDivisibleBy2 = ( inputNumber ) => {
    let count = 0;
    if (inputNumber < 0) {
        return -1;
    }
  
    if (inputNumber % 5 === 0) {
        while (inputNumber % 10 !== 0) {
            inputNumber *= 2;
            count++;
        }
        return count;
    
    else {
        return -1;
    }
};
console.log(checkDivisibleBy2(-10));


Output

-1


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads