杂耍人序列 |第 2 组(使用递归)
杂耍者序列是一系列整数,其中第一项以正整数a开头,其余项使用以下递归关系从前一项生成:
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
给定一个数字N ,我们必须打印这个数字的杂耍者序列作为序列的第一项。
例子:
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
迭代方法:我们已经在这个问题的Set 1中看到了迭代方法。
递归方法:在这种方法中,我们将从 N 开始递归遍历。对于每个递归步骤,请按照以下步骤操作
- 输出N的值
- 如果 N达到 1则结束递归
- 否则,根据奇数或偶数遵循公式,并在新导出的数字上调用递归函数。
下面是该方法的实现:
C++
// C++ code for the above approach
#include
using namespace std;
// Recursive function to print
// the juggler sequence
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);
}
}
// Driver code
int main()
{
// Juggler sequence starting with 10
jum_sequence(10);
return 0;
}
// This code is contributed by Potta Lokesh
Java
// Java code for the above approach
class GFG
{
// Recursive function to print
// the juggler sequence
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);
}
}
// Driver code
public static void main(String args[]) {
// Juggler sequence starting with 10
jum_sequence(10);
}
}
// This code is contributed by Saurabh Jaiswal
Python3
# Python code to implement the above approach
# Recursive function to print
# the juggler sequence
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)
# Juggler sequence starting with 10
jum_sequence(10)
C#
// C# code for the above approach
using System;
class GFG{
// Recursive function to print
// the juggler sequence
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);
}
}
// Driver code
public static void Main()
{
// Juggler sequence starting with 10
jum_sequence(10);
}
}
// This code is contributed by Saurabh Jaiswal
Javascript
输出:
10 3 5 11 36 6 2 1
时间复杂度: O(N)
辅助空间: O(1)