w3resource

JavaScript: Smallest number whose digits multiply to a number

JavaScript Math: Exercise-113 with Solution

Write a JavaScript program to calculate the smallest number whose digits multiply to a given number.

Example:
let n =100

Test Data:
(100) -> 455
(120) -> 358
(16) -> 28
(129) -> 0

Sample Solution:

HTML Code:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JavaScript program to Smallest number whose digits multiply to a number</title>
</head>
<body>

</body>
</html>

JavaScript Code:

function test(n) {
	if (n < 10) return n;
	data = [];
	for (i = 9; i > 1; i--) {
		// Store all occurrences of current digit in data 
        // if current digit divides n.
		while (n % i === 0) {
			n = n / i;
			data.push(i);
		}
	}

	if (n != 1) return 0;
	result = 0;
	for (i = data.length - 1; i >= 0; i--) {
		result = result * 10 + data[i];
		if (result > Number.MAX_VALUE) return 0;
	}
	return result;
}
n = 100
console.log("n = " + n)
console.log("Smallest number whose digits multiply to the said number: " + test(n));
n = 120
console.log("n = " + n)
console.log("Smallest number whose digits multiply to the said number: " + test(n));
n = 16
console.log("n = " + n)
console.log("Smallest number whose digits multiply to the said number: " + test(n));
n = 129
console.log("n = " + n)
console.log("Smallest number whose digits multiply to the said number: " + test(n));

Sample Output:

n = 100
Smallest number whose digits multiply to the said number: 455
n = 120
Smallest number whose digits multiply to the said number: 358
n = 16
Smallest number whose digits multiply to the said number: 28
n = 129
Smallest number whose digits multiply to the said number: 0

Flowchart:

JavaScript: Smallest number whose digits multiply to a number.

Live Demo:

See the Pen javascript-math-exercise-113 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus

Previous: Maximum value swapping two digits in an integer.
Next: Check a given number is self-dividing or not.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.

JavaScript: Tips of the Day

Shorten an array using its length property

A great way of shortening an array is by redefining its length property.

let array = [0, 1, 2, 3, 4, 5, 6, 6, 8, 9]
array.length = 4
// Result: [0, 1, 2, 3]

Important to know though is that this is a destructive way of changing the array. This means you lose all the other values that used to be in the array.

Ref: https://bit.ly/2LBj213