Home  >  Article  >  Web Front-end  >  JavaScript Fun Question: Building a House

JavaScript Fun Question: Building a House

黄舟
黄舟Original
2017-02-15 14:11:361734browse

We plan to build a house with N floors. Its design blueprint is as follows:

The volume of the bottom floor is N# To the ##3 power, the volume of the penultimate layer is (N-1) to the 3 power, and so on, the volume of the top layer is 1 to the 3 power.

Now comes the problem. Due to various factors, the designer decided to limit the total volume to

M.

Is it possible that the

M volume is just right to build this house?

Please note, no more, no less.

If possible, please return the layer number

N.

The function prototype is as follows:

findNb (M)

The return value is an integer. If it cannot be done, please Return

-1.


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

Idea:

I have given the total volume

M, then start from the top layer and subtract each layer in turn volume until M<=0. If

is equal to

0, that is, the house can be built and the number of floors is returned. If

is a negative number, it means that the volume

M is inappropriate and -1 will be returned.

function findNb(m) {
    var nb = 1;
    while(m > 0){
        m -= Math.pow(nb++,3);
    }
    return m == 0 ? nb - 1 : -1;
}

The above is the content of JavaScript interesting questions: building a house. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn