Task
I solve the problem on Codewars : find for the following formula n^3 + (n-1)^3 + ... + 1^3 = m number n . The number m is known and passed to the FindNb function. If n does not exist for the passed m , then the answer is -1. For example:
FindNb(1071225) --> 45
FindNb(91716553919377) --> -1
My decision
This is what I did:
public static long FindNb(long m) { long sum = 0; var nResult = 0; for (var i = 1; sum < m; i++) { sum = 0; nResult = i; for (var nMaybe = i; nMaybe > 0; nMaybe--) { sum += (long)Math.Pow(nMaybe, 3.0); } } if (sum != m) { nResult = -1; } return nResult; } Question
My solution works , but the service requires optimizing the code (it takes too long to complete). How to do it?
- the complexity of my algorithm was quadratic (N ^ 2). I do not know how to reduce it.
- I also thought the cast could
...(long)Math.Pow...slows down the code, but the search for optimization in this part also did not work.
