Given a product, I want to find the most simplified base and its corresponding exponent. For instance, a product of 343 would yield a base of 7 and exponent of 3. If a certain product returns multiple sets of bases and exponents, only the simplest base is considered. For example, the product of 64 would return a base of 2 and exponent of 6, and eliminate the higher combinations of base 4 and exponent 3 and base 8 and exponent 2.
Now, I've already written a program that works for this scenario. However, it seems to be relatively unorthodox and can take a long time to compile given high numbers for the product argument specified. Is there a better and more efficient way of writing the function, possibly by using logarithms? I can't seem to find anything on this type of programming problem.
function findBaseAndExponent(product) {
product = Math.round(product);
var base = 0;
var exp = 0;
var abort = false;
for (var i = 1; i <= product && !abort; i++) {
for (var j = 1; j <= product && !abort; j++) {
const currProd = Math.pow(i, j);
if (currProd == product) {
base = i;
exp = j;
abort = true;
}
if (currProd > product){
break;
}
}
}
if (base == product && exp == 1) {
base = "N/A";
exp = "N/A";
}
return { "base": base, "exponent": exp };
}
console.log(findBaseAndExponent(343)); // Output: { base: 7, exponent: 3 }
console.log(findBaseAndExponent(64)); // Output: { base: 2, exponent: 6 }
console.log(findBaseAndExponent(41)); // Output: { base: N/A, exponent: N/A }