Build a pile of Cubes

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

Good Solution1:

public class ASum {
  
  public static long findNb(long m) {
    long mm = 0, n = 0;
    while (mm < m) mm += ++n * n * n;
    return mm == m ? n : -1;
  }  
}

Good Solution2:

public class ASum {
  
  public static long findNb(long m) {
    long total = 0;
    int counter = 0;
    
    while (total < m) {    
      counter++;  
      total = total + (long) Math.pow(counter, 3);            
    }
    
    if (m == total)
      return counter;
    return -1;
  }  
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 10,131评论 0 23
  • 有心为善,虽善不赏;无心为恶,虽恶不罚。 ——《聊斋志异》 开...
    Aa土豆阅读 666评论 16 3
  • “姐姐,我一定可以考上那所好大学的。” “光说不做假把式。” “呀,我一直都在努力的学习。” “呵呵。” “姐姐,...
    阿俊xi阅读 174评论 2 1
  • 我们经常会在网页,以及各种应用软件中见到多层树形结构。一般很多菜单,在数据库中存储时采用如下结构: id:当前项i...
    赵仝阅读 2,286评论 1 2
  • 人类的第一语言不是汉语,也不是英语,而是图像。仔细想想,的确如此。在我们从儿童时期,拿起笔的瞬间,就会在纸...
    艾颜Joy阅读 982评论 0 0