6kyu Build a pile of Cubes
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; }總結
以上是生活随笔為你收集整理的6kyu Build a pile of Cubes的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 5kyu k-Primes
- 下一篇: 5kyu Some Egyptian f