美文网首页
Build a pile of Cubes

Build a pile of Cubes

作者: Magicach | 来源:发表于2017-12-26 19:00 被阅读0次

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;
  }  
}

相关文章

网友评论

      本文标题:Build a pile of Cubes

      本文链接:https://www.haomeiwen.com/subject/zwhsgxtx.html