using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CSharpTest
{
class Class1
{
public void jishuan(int n)
{
int m = (int)Math.Pow(n, 3);
int[] ary = new int[n];
int fir = n * (n - 1) + 1;
Console.Write(n + "^3=" + fir);
for (int i = 1; i < n; i++)
{
fir = fir + 2;
Console.Write("+" + fir);
}
Console.Write("=" + m);
}
}
}
第二种方法:
public void js(int n)
{
int m = (int)Math.Pow(n, 3);
int sum = 0;
for (int a = 1; a < (m / 2); a += 2)// m/2因为最大的奇数不会超过这个n^3的一半
{
int fir = a;
sum = a;
for (int i = 1; i < n; i++)
{
fir = fir + 2;
sum +=fir;
}
if (sum != m)
{
continue;
}
else
{
Console.Write(n + "^3=" + a);
for (int i = 1; i < n; i++)
{
a = a + 2;
Console.Write("+" + a);
}
return; //得到想要的结果就停止,节省时间
}
}
}