代码如下:
1.用两层循环
static void Main(string[] args)
{
for(int i=-500;i<500;i++)
{
int temp=i;
int point=0;
bool hasResult = false;
for(int j=(i+1);j<500;j++)
{
temp+=j;
if(temp>500) break;
if(temp==500)
{
hasResult = true;
point = j;
break;
}
}
if(hasResult)
{
Console.Write(i);
for(int k=(i+1) ;k<=point ; k++)
{
Console.Write("+"+k);
}
Console.WriteLine("=500/n");
}
}
}
2.用单层循环来做
我的代码,答案和算法。
public static void Main()
{
int m;
int r = 1000;
int n = 1;
int loopNum = 0;
while( r > n )
{
loopNum++;
n++;
m = ( 1000 / n + n - 1 ) / 2;
if ( r % n == 0 && ( 1000 / n + n - 1) % 2 == 0 && m - n + 1 > 0 )
{
Console.Write( "500: " );
for( int t = m - n + 1; t <= m; t ++ )
{
Console.Write( "{0} ", t );
}
Console.WriteLine();
r = r / n;
}
}
Console.WriteLine( "Total Loop {0}", loopNum );
Console.ReadLine();
}
500: 98 99 100 101 102
500: 59 60 61 62 63 64 65 66
500: 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
Total Loop 24
假设最后一个是m,数组个数是n.第一个数是m-n+1.它们的和是(m-n+1+m)*n = 500,m=( 1000 / n + n - 1 ) / 2; 要求m是整数,m-n+1>0.