6kyu Build a pile of Cubes

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wobeatit/article/details/88630234

6kyu Build a pile of Cubes

题目背景:

Task:

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.

题目分析:

此处有一个数学公式需要记忆: 1^3 +…+ n^3 = (1+2+…+n)^2,依据这个性质,可以在O(1)时间复杂度上完成此道题的求解。

AC代码:

#include<math.h>
class ASum {
  public:
  static long long findNb(long long m);
};
// hint: 1^3 +...+ n^3 = (1+2+...+n)^2
long long ASum::findNb(long long m) {
    long long sqrt1 = sqrt(m);
    if (sqrt1 * sqrt1 == m ) {
        long long n = floor(sqrt(2 * sqrt1));
        if ( n * ( n + 1 ) == 2 * sqrt1 ) return n;
        else return -1;
    }
    else return -1;
}

猜你喜欢

转载自blog.csdn.net/wobeatit/article/details/88630234