Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Finding a number, when multiplied with input number yields input number in JavaScript
We need to write a JavaScript function that takes a positive integer n and a positive integer p, then finds a value k such that the sum of digits raised to successive powers equals k * n.
Problem Statement
Given a number n with digits a, b, c, d... and a power p, we want to find integer k where:
(a^p + b^(p+1) + c^(p+2) + d^(p+3) + ...) = n * k
If such k exists, return k; otherwise return -1.
Example Walkthrough
For number 695 and p = 2:
- 6^2 + 9^3 + 5^4 = 36 + 729 + 625 = 1390
- Check if 1390 / 695 is an integer: 1390 / 695 = 2
- Since 2 is an integer, k = 2
Solution
const num = 695;
const p = 2;
const findDesiredNumber = (num, p) => {
let sum = 0;
let str = String(num);
let power = p;
// Calculate sum of digits raised to successive powers
for(let i = 0; i < str.length; i++){
const digit = parseInt(str[i]);
sum += Math.pow(digit, power);
power++;
}
// Check if sum/num is an integer
return Number.isInteger(sum / num) ? sum / num : -1;
};
console.log(`Number: ${num}, Power: ${p}`);
console.log(`Result: ${findDesiredNumber(num, p)}`);
Number: 695, Power: 2 Result: 2
Testing with Different Values
const findDesiredNumber = (num, p) => {
let sum = 0;
let str = String(num);
let power = p;
for(let i = 0; i < str.length; i++){
const digit = parseInt(str[i]);
sum += Math.pow(digit, power);
power++;
}
return Number.isInteger(sum / num) ? sum / num : -1;
};
// Test cases
console.log("Testing 46 with p=1:", findDesiredNumber(46, 1)); // 4^1 + 6^2 = 40, 40/46 ? 0.87
console.log("Testing 89 with p=1:", findDesiredNumber(89, 1)); // 8^1 + 9^2 = 89, 89/89 = 1
console.log("Testing 695 with p=2:", findDesiredNumber(695, 2)); // 6^2 + 9^3 + 5^4 = 1390, 1390/695 = 2
Testing 46 with p=1: -1 Testing 89 with p=1: 1 Testing 89 with p=2: 1 Testing 695 with p=2: 2
How It Works
The algorithm converts the number to a string to access individual digits, then:
- Iterates through each digit
- Raises each digit to successive powers starting from p
- Sums all the powered values
- Checks if sum/n produces an integer result
Conclusion
This function efficiently finds the multiplier k by calculating the sum of digits raised to successive powers and checking divisibility. It returns the integer quotient if valid, otherwise -1.
Advertisements
