스터디/알고리즘

[알고리즘][C++] 연속된 자연수의 합

y00&z1 2022. 8. 2. 22:03

n을 2로 나눈 다음에 더하면 되지 않을까?

 

 

15

- (1 + 2) 

= 12 

 

if (12 % 2 == 0 )  

12/2 의 몫을

1,2에 분배  

 

1     2

+6 +6

7     8 

=> 7+8=15

 

======

 

15

-( 1 + 2 + 3) 

= 9 

 

if (9%3 == 0)

9/3의 몫을

1 2 3에 분배

 

1     2    3

+3 +3 +3

4     5    6

=> 4+5+6 = 15

 

 

#include <stdio.h>
#include <vector>
#include <algorithm>
using namespace std;

int main(){ 
	//freopen("input.txt", "rt", stdin);
	int a, b=1, cnt=0, tmp, i; 
	
	scanf("%d", &a);
	tmp=a;
	a--; //a=14
	
	while(a>0){
		b++;//b=2인 상태
		a=a-b; //a=12 
		if(a%b==0){ //연속된 자연수의 개수 == b 
			for(i=1; i<b; i++){
				printf("%d + ", (a/b)+i);
			}
			printf("%d = %d\n", (a/b)+i, tmp);
			cnt++;
		}
	}

	printf("%d", cnt);
	
	return 0;
}