We are provided with a number N. Our task is to generate all the Hailstone Numbers from N and find the number of steps taken by N to reduce to 1.
Collatz Conjecture: A problem posed by L. Collatz in 1937, also called the 3x+1 mapping, 3n+1 problem. Let N be a integer. According to Collatz conjecture, if we keep iterating N as following
N = N / 2 // For Even N
and N = 3 * (N-1) + 1 // For Odd N
Our number will eventually converge to 1 irrespective of the choice of N.
Hailstone Numbers: The sequence of integers generated by Collatz conjecture are called Hailstone Numbers.
Input : N = 7 Output : Hailstone Numbers: 7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1 No. of steps Required: 17 Input : N = 9 Output : Hailstone Numbers: 9, 28, 14, 7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1 No. of steps Required: 20 In the first example, N = 7. The numbers will be calculated as follows: 7 3 * 7 + 1 = 22 // Since 7 is odd. 22 / 2 = 11 // 22 is even. 3 * 11 + 1 = 34 // 11 is odd. .... and so on upto 1.
The idea is simple, we recursively print numbers until we reach base case.
7 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1 Number of Steps: 17
This article is contributed by Vineet Joshi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Numbers less than N which are product of exactly two distinct prime numbers
- Print N lines of 4 numbers such that every pair among 4 numbers has a GCD K
- Maximum sum of distinct numbers such that LCM of these numbers is N
- Count numbers which can be constructed using two numbers
- Count numbers which are divisible by all the numbers from 2 to 10
- Absolute difference between the Product of Non-Prime numbers and Prime numbers of an Array
- Absolute Difference between the Sum of Non-Prime numbers and Prime numbers of an Array
- Print numbers such that no two consecutive numbers are co-prime and every three consecutive numbers are co-prime
- Sum of first n even numbers
- Add two numbers using ++ and/or --
- Sum of all even numbers in range L and R
- GCD of factorials of two numbers
- Sum of cubes of first n even numbers
- Undulating numbers
- Tribonacci Numbers
Improved By : Mithun Kumar