使用C#实现求出若干组整数之和为500的连续序列(web面试题)

无意间在网上看到这个计算题.小弟闲暇时写了一下.求有木有更便捷的写法

 1  private void button1_Click(object sender, EventArgs e)
2 {
3 //先求出最多有多少个整数相加.明显从1开始
4 int a = 0;
5 int bignum = 0;
6 for (int i = 1; i <=500; i++)
7 {
8 if (a <= 500)
9 {
10 a = a + i;
11 bignum = i;
12 }
13 }
14 string s = "";
15
16 for (int j = 1; j <=500; j++)
17 {
18 int c = 0;
19 int d = j;
20 for (int k= 1;k <= bignum; k++)
21 {
22 c=j+ k;
23 d += c;
24 if (d == 500)
25 {
26 s = j.ToString() + "-" + k.ToString() + ",";
27 }
28 }
29 }
30 MessageBox.Show(s);
31 }

 

你可能感兴趣的:(Web)