Juggler Sequence is a series of integer number in which the first term starts with a positive integer number a and the remaining terms are generated from the immediate previous term using the below recurrence relation :

Juggler Sequence starting with number 3:
5, 11, 36, 6, 2, 1
Juggler Sequence starting with number 9:
9, 27, 140, 11, 36, 6, 2, 1
Given a number N, we have to print the Juggler Sequence for this number as the first term of the sequence.
Examples:
Input: N = 9
Output: 9, 27, 140, 11, 36, 6, 2, 1
We start with 9 and use above formula to get next terms.
Input: N = 6
Output: 6, 2, 1
Iterative approach: We have already seen the iterative approach in Set 1 of this problem.
Recursive approach: In this approach, we will recursively traverse starting from N. Follow the steps below for each recursive step
- Output the value of N
- If N has reached 1 end the recursion
- Otherwise, follow the formula based on the number being odd or even and call the recursive function on the newly derived number.
Below is the implementation of the approach:
C++
#include <bits/stdc++.h>
using namespace std;
void jum_sequence(int N)
{
cout << N << " ";
if (N <= 1)
return;
else if (N % 2 == 0)
{
N = floor(sqrt(N));
jum_sequence(N);
}
else
{
N = floor(N * sqrt(N));
jum_sequence(N);
}
}
int main()
{
jum_sequence(10);
return 0;
}
|
Java
class GFG
{
public static void jum_sequence(int N) {
System.out.print(N + " ");
if (N <= 1)
return;
else if (N % 2 == 0) {
N = (int) (Math.floor(Math.sqrt(N)));
jum_sequence(N);
} else {
N = (int) Math.floor(N * Math.sqrt(N));
jum_sequence(N);
}
}
public static void main(String args[]) {
jum_sequence(10);
}
}
|
Python3
def jum_sequence(N):
print(N, end =" ")
if (N == 1):
return
elif N & 1 == 0:
N = int(pow(N, 0.5))
jum_sequence(N)
else:
N = int(pow(N, 1.5))
jum_sequence(N)
jum_sequence(10)
|
C#
using System;
class GFG{
public static void jum_sequence(int N)
{
Console.Write(N + " ");
if (N <= 1)
return;
else if (N % 2 == 0)
{
N = (int)(Math.Floor(Math.Sqrt(N)));
jum_sequence(N);
}
else
{
N = (int)Math.Floor(N * Math.Sqrt(N));
jum_sequence(N);
}
}
public static void Main()
{
jum_sequence(10);
}
}
|
Javascript
<script>
function jum_sequence(N){
document.write(N +" ");
if (N <= 1)
return;
else if (N % 2 == 0)
{
N = Math.floor(Math.sqrt(N));
jum_sequence(N);
}
else
{
N = Math.floor(N * Math.sqrt(N));
jum_sequence(N);
}
}
jum_sequence(10);
</script>
|
Output:
10 3 5 11 36 6 2 1
Time Complexity: O(N)
Auxiliary Space: O(1)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
07 Dec, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...