So I was searching for a way to print multiplication table using recursion and all the solution I came across were to use 2 parameters. So I would like to know if there is anyway to do the same thing but only using 1 param? (using loop is prohibited) Expected Output:
n=4:
4 x 1 = 4
4 x 2 = 8
4 x 3 = 12
4 x 4 = 16
4 x 5 = 20
4 x 6 = 24
4 x 7 = 28
4 x 8 = 32
4 x 9 = 36
4 x 10 = 40
Here is my code:
public class multiTable {
public static void rec(int n,int i){
if(i>10){
return;
}
System.out.println(n " x " i " = " n*i);
rec(n,i 1);
}
public static void main(String[] args) {
rec(4,1);
}
}
So I'm wondering if there is something we can do to use only 1 parameter (omitting "int i" from the function argument) and receive the same result.
CodePudding user response:
You can encode the two arguments into one. The mapping is (n, i) -> (11*n i), and the inverse mapping is (n) -> (n/11, n). This works assuming i is between 0 and 10, and n isn't so big that you overflow an int.
Here's the new code:
public class multiTable {
public static void rec(int n){
System.out.println((n/11) " x " (n) " = " (n)*(n/11));
if (n < 10) {
rec(n 1);
}
}
public static void main(String[] args) {
rec(4*11 1);
}
}
CodePudding user response:
Let me preface this by saying that this is a stunt. There's no motivation whasoever for writing real code this way using recursion. What you want to do calls for a loop. Having said that...
Here's a way using a closure. rec
takes one argument and func
takes one argument. I believes this satisfies the specifications you have set out, because it is technically "only using 1 param". The function gains access to n
by way of a closure and calls itself recursively by way of an interface.
class Example {
public interface Fn {
void func(int i);
}
public static void rec(int n) {
Fn fn;
fn = new Fn() {
public void func(int i) {
if (i > 10) return;
System.out.println(n " x " i " = " n*i);
this.func(i 1);
}
};
fn.func(1);
}
public static void main(String[] args) {
rec(4);
}
}
PS: this same approach would be easier in other languages: e.g. JavaScript.
const rec = n => {
const fn = i => {
if (i > 10) return;
console.log(n " x " i " = " n*i);
fn(i 1);
}
fn(1);
}
rec(4);