-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathRecursion-3
More file actions
69 lines (60 loc) · 2.25 KB
/
Recursion-3
File metadata and controls
69 lines (60 loc) · 2.25 KB
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
Q1 - Given a number n, print the following pattern without using any loop.
n, n-5, n-10, ..., 0, 5, 10, ..., n-5, n
Input = 16
Expected Output 16, 11, 6, 1, -4, 1, 6, 11, 16
import java.util.*;
import java.util.Scanner;
public class Test{
public static void main(String[] args){
Scanner scn = new Scanner(System.in);
System.out.println("Enter the number n: ");
int n = scn.nextInt();
rec(n, n, true);
}
public static void rec(int n, int m, boolean flag) {
System.out.print(m + " ");
// If we are moving back towards n and we have reached there, then we are done
if (flag == false && n == m)
return;
// If we are moving towards 0 or negative.
if (flag) {
// If m is greater, then 5, recur with true flag
if (m - 5 > 0)
rec(n, m - 5, true);
else // recur with false flag
rec(n, m - 5, false);
}
else // If flag is false.
rec(n, m + 5, false);
}
}
Q2 - Find m-th summation of first n natural numbers where m-th summation of first n natural
numbers is defined as following:
If m > 1: SUM(n, m) = SUM(SUM(n, m - 1), 1)
Else :SUM(n, 1) = Sum of first n natural numbers.
import java.util.*;
import java.util.Scanner;
public class Test{
public static void main(String[] args){
Scanner scn = new Scanner(System.in);
System.out.println("Enter the number n and m: ");
int n = scn.nextInt();
int m = scn.nextInt();
System.out.println(rec(n, m));
}
public static int rec(int n, int m) {
if (m == 1)
return sumofn(n);
int sum = rec(n, m - 1);
return sumofn(sum);
}
public static int sumofn(int n){
int ans = 0;
if(n == 1){
ans++;
return ans;
}
ans += n + sumofn(n-1);
return ans;
}
}