已知和求等差立方和数列的最大项#JS_codewar_7

题目

Description:

Your task is to construct a building which will be a pile of n cubes. The cube at the bottom will have a volume of n^3, the cube above will have volume of (n-1)^3 and so on until the top which will have a volume of 1^3.

You are given the total volume m of the building. Being given m can you find the number n of cubes you will have to build?

The parameter of the function findNb (find_nb, find-nb, findNb) will be an integer m and you have to return the integer n such as n^3 + (n-1)^3 + ... + 1^3 = m if such a n exists or -1 if there is no such n.

Examples:

findNb(1071225) --> 45
findNb(91716553919377) --> -1

我的解

function findNb(m) {
    let n = parseInt(Math.pow(m, 1/2));
    console.log(n);
    if (n !== Math.pow(m, 1/2)) {
        return (-1);
    } else {
        let nn = 2 * n;
        let p = parseInt(Math.pow(nn, 1/2));
        if (p * (p+1) == nn) {
            return p;
        } else {
            return (-1);
        }
    }
}

我的感想

卡了很久,最后百度到了公式,所以解决了
不忍心n从0一直++
对于这种题,看答案也没什么更巧妙的了
只是还是不太会用 ()? A:B

你可能感兴趣的:(已知和求等差立方和数列的最大项#JS_codewar_7)