【IT面试题002】将一个正整数拆成几个连续整数之和

/*
将一个正整数拆成几个连续整数之和代码
 sum = a + (a+1) + (a + n - 1)
 => 2 * sum = n * (2a + n - 1)
*/

/*
将一个正整数写成若干个整数之和,打印出所有的可能,每种和输出时,加数升序排列
*/
#include "stdafx.h"

#include <iostream>
#include <string>
#include <vector>
#include <cmath>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
	int sum = 55;
	int sum2 = sum * 2;
	int n;
	int a;
	int upper = (int)sqrt(double(sum2));
	for (n = 1;n <= upper;n++ )
	{
		if (sum2 % n == 0)
		{
			int temp = sum2 / n - n + 1;
			if (temp%2 == 0)
			{
				a = temp / 2;
				//得到了一个解
				for(int i = 0;i<n;i++)
				{
					cout << a + i << " ";
				}
				cout << endl;
			}
		}
	}
}


posted on 2011-06-04 18:07  speedmancs  阅读(661)  评论(0编辑  收藏  举报

导航