Since I've never done any performance programming (Aside from the better choices such as array vs list etc. The real basics.), I should probably read up on it. But I had to start somewhere, so, someone I know - which is a much better programmer than I am - tasked me with making this "assignment":
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
) will be an integerm
and you have to return the integern
such as \$n^3 + (n-1)^3 + \dots + 1^3 = m\$ if such an
exists or-1
if there is no suchn
.
He gave me this template with it:
using System;
public class Program
{
public static void Main()
{
Console.WriteLine(findNb(4183059834009));
Console.WriteLine(findNb(24723578342962));
Console.WriteLine(findNb(135440716410000));
Console.WriteLine(findNb(40539911473216));
}
public static long findNb(long m)
{
}
}
In which I inserted:
for(long n = 1; n < (m / 3); n++)
{
double vol = 0;
for(long i = 0; i < n; i++)
vol += Math.Pow((n - i), 3);
if(vol > m)
return -1;
if(vol == m)
return n;
}
return -1;
This code works, but it takes incredibly long for the larger numbers, as is my main problem.
What can I do to shorten the time it takes for this code takes to complete?