I hope it is OK to post problems that I am having on other sites. The only reason I switched from FCC was to beef up on JS practice before I continued on with FCC curriculum.
I have been trying to solve this for nearly 2 days and I think I am spinning my wheels at this point.
Problem: Trying to solve this codewars problem. In case the link is blocked for any reason, this is description of the problem:
A perfect power is a classification of positive integers:
In mathematics, a perfect power is a positive integer that can be expressed as an integer power of another positive integer. More formally, n is a perfect power if there exist natural numbers m > 1, and k > 1 such that mk = n.
Your task is to check wheter a given integer is a perfect power. If it is a perfect power, return a pair
m
andk
with mk = n as a proof. Otherwise returnNothing
,Nil
,null
,NULL
,None
or your language’s equivalent.Note: For a perfect power, there might be several pairs. For example
81 = 3^4 = 9^2
, so(3,4)
and(9,2)
are valid solutions. However, the tests take care of this, so if a number is a perfect power, return any pair that proves it.
And this is my code:
// alert ("is this mike on?");
function perfectpower(n){
//Get square root of n;
var sqrtn = Math.sqrt(n);
// console.log(sqrtn);
//Get list of x: x >> sqr rt of n;
var x = Array.apply(null, Array(sqrtn+1)).map(function (_, i) {return i;});
var y = [...Array(10).keys()];
// console.log("This is x: " + x);
// console.log("This is the length of x: " + x.length);
//
// console.log("This is y: " + y);
// console.log("This is the length of y: " + y.length);
// Calc each x^2,3,4 etc
var perfects = [];
var message = null;
for(var i = 2; i<x.length; i++){
for(var j = 2; j<y.length; j++){
var xtothey = (Math.pow(x[i],y[j]));
// console.log("i is: " + i);
// console.log("j is: " + j);
// console.log("xtothey is: " + xtothey);
if(xtothey === n){
perfects.push(x[i],y[j]);
message = "";
}else if (xtothey !== n){
//do nothing
}
}
}
return perfects;
}
The testcase that is failing right now is:
perfectpower(5)
This is the error I am getting:
RangeError: Invalid array length
It should return null or nothing but I also need to keep looping through to find perfect power pairs that might come later in the loop.
Part of the problem could be that I had never heard of perfect powers before today and so have the most minimal grasp of exactly how to solve for them. This was a little helpful: link in so far as it helped me develop the basic steps that I needed to code for.
Thank you.