Generate a Bitonic array starting with N and adjacent difference of K
Last Updated :
06 Jul, 2021
Given two integers N and K, the task is to generate a bitonic array where the first element is N and every element is at the difference of K.
Examples:
Input: N = 10, K = 5
Output: 10 5 0 5 10
Input: N = 16, K = 5
Output: 16 11 6 1 -4 1 6 11 16
Approach: The idea is to use recursion to solve this problem. As stated in the problem, the first element of the bitonic array is N. Therefore, append it into the array and solve for the N. Below is the recursive function definition:
- Base Case: When the value of N is less than equal to 0, Then return 1 because now the values will increase.
- Recursive Case: If the value of the N is greater than , Then append N – K and recursively call for the N – K and finally append N.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int decreseq( int n, int k)
{
if (n > 0) {
cout << n - k << " " ;
decreseq(n - k, k);
}
if (n <= 0)
return 1;
cout << n << " " ;
return 1;
}
int main()
{
int n = 10, k = 5;
cout << n << " " ;
decreseq(n, k);
return 0;
}
|
Java
import java.util.*;
class GFG{
static int decreseq( int n, int k)
{
if (n > 0 )
{
System.out.print(n - k + " " );
decreseq(n - k, k);
}
if (n <= 0 )
return 1 ;
System.out.print(n + " " );
return 1 ;
}
public static void main(String[] args)
{
int n = 10 , k = 5 ;
System.out.print(n+ " " );
decreseq(n, k);
}
}
|
Python3
def decreseq(n, k):
if (n > 0 ):
print (n - k, end = " " );
decreseq(n - k, k);
if (n < = 0 ):
return 1 ;
print (n, end = " " );
return 1 ;
n = 10 ; k = 5 ;
print (n, end = " " );
decreseq(n, k);
|
C#
using System;
class GFG{
static int decreseq( int n, int k)
{
if (n > 0)
{
Console.Write(n - k + " " );
decreseq(n - k, k);
}
if (n <= 0)
return 1;
Console.Write(n + " " );
return 1;
}
public static void Main(String[] args)
{
int n = 10, k = 5;
Console.Write(n + " " );
decreseq(n, k);
}
}
|
Javascript
<script>
function decreseq(n, k)
{
if (n > 0) {
document.write( n - k + " " );
decreseq(n - k, k);
}
if (n <= 0)
return 1;
document.write( n + " " );
return 1;
}
var n = 10, k = 5;
document.write( n + " " );
decreseq(n, k);
</script>
|
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...