-
Notifications
You must be signed in to change notification settings - Fork 0
/
isStacked
30 lines (27 loc) · 1.09 KB
/
isStacked
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
Define a stacked number to be a number that is the sum of the first n positive integers for some n. The first 5 stacked numbers are
1= 1
3 = 1 +2
6 = 1 +2 + 3
10 = 1 + 2 + 3+ 4
15 = 1 + 2 + 3 + 4 + 5
Note that from the above we can deduce that 7, 8, and 9 are not stacked numbers because they cannot be the sum of any sequence of positive integers that start at 1.
Write a function named isStacked that returns 1 if its argument is stacked. Otherwise it returns 0. Its signature is:
int isStacked(int n);
So for example, isStacked(10) should return 1 and isStacked(7) should return 0.
Solutions
// this function checks if a number is a stacked number by looping as long as number given is greater than sum
// at last we check if the number is equal to the calculated sum
public static int isStacked(int n) {
int sum = 1;
int j = 1;
while (sum < n) {
j++;
sum += j;
}
// check the sum that you ended up with is same as a given number
if (sum == n) {
return 1;
}else{
return 0;
}
}