-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathfindConsecutive.cpp
More file actions
50 lines (43 loc) · 964 Bytes
/
findConsecutive.cpp
File metadata and controls
50 lines (43 loc) · 964 Bytes
1
2
3
4
5
6
7
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// C++ program to print consecutive sequences that add to a given value
#include<bits/stdc++.h>
using namespace std;
void findConsecutive(int N)
{
// Note that we don't ever have to sum
// numbers > ceil(N/2)
int start = 1, end = (N+1)/2;
// Repeat the loop from bottom to half
while (start < end)
{
// Check if there exist any sequence
// from bottom to half which adds up to N
int sum = 0;
for (int i = start; i <= end; i++)
{
sum = sum + i;
// If sum = N, this means consecutive
// sequence exists
if (sum == N)
{
// found consecutive numbers! print them
for (int j = start; j <= i; j++)
printf("%d ", j);
printf("\n");
break;
}
// if sum increases N then it can not exist
// in the consecutive sequence starting from
// bottom
if (sum > N)
break;
}
sum = 0;
start++;
}
}
int main()
{
int N = 125;
findConsecutive(N);
return 0;
}