Stack Overflow in Recursion for big value of n

43 views Asked by At

How Can I Fix this Stack Overflow for Big value of n? It is working fine for small integers. I have been attached the question link for reference. https://codeforces.com/contest/1208/problem/A Can we do it by iterative method?

import java.util.Scanner;

public class XORinacci {

  public static int Rinacci(int a, int b, int n) {
    if (n == 0) return a; else if (n == 1) return b;

    return Rinacci(a, b, n - 1) ^ Rinacci(a, b, n - 2);
  }

  
  public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    int T = scan.nextInt();
    int arr[] = new int[T];
    int a, b, n;
    for (int i = 0; i < T; i++) {
      a = scan.nextInt();
      b = scan.nextInt();
      n = scan.nextInt();
      arr[i] = Rinacci(a, b, n);
    }
    for (int i = 0; i < arr.length; i++) {
      System.out.println(arr[i]);
    }
    scan.close();
  }
}
0

There are 0 answers