-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathHailstone_sequence.cpp
69 lines (59 loc) · 1.32 KB
/
Hailstone_sequence.cpp
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
// CPP program to find Hailstone Sequence of a given number N up to 1
/*
The Hailstone sequence of numbers can be generated from a starting positive integer, N by:
If N = 1, then the sequence ends.
If N is even, then the next N of the sequence = N / 2
If N is odd, then the next N of the sequence = (3 * N) + 1
*/
#include <bits/stdc++.h>
using namespace std;
int HailstoneSequence(int N)
{
static int count;
if (N == 1 && count == 0)
{
cout << N << " ";
return count;
}
else if (N == 1 && count != 0)
{
cout << N << " ";
count++;
return count;
}
else if (N % 2 == 0)
{
cout << N << " ";
count++;
HailstoneSequence(N / 2);
}
else if (N % 2 != 0)
{
cout << N << " ";
count++;
HailstoneSequence(3 * N + 1);
}
}
// Driver code
int main()
{
int N, ans;
cout << "Enter a number: ";
cin >> N;
cout << "\nHailstone Sequence upto 1:" << endl;
ans = HailstoneSequence(N);
cout <<"\n\nNumber of Steps involved: "<< ans << endl;
return 0;
}
/*
OUTPUT 1:
Enter a number: 7
Hailstone Sequence upto 1:
7 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1
Number of Steps involved: 17
OUTPUT 2:
Enter a number: 6
Hailstone Sequence upto 1:
6 3 10 5 16 8 4 2 1
Number of Steps involved: 9
*/