(Hacker Rank) Fibonacci Modified - Solution

Link to the problem: https://www.hackerrank.com/challenges/fibonacci-modified

The problem here is that the result may be a very large number that cannot be supported by the primitive types int and long. Then, it is necessary to use the data type BigInteger.


import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
       
        BigInteger n1 = BigInteger.valueOf(sc.nextLong());
        BigInteger n2 = BigInteger.valueOf(sc.nextLong());
        int nth = sc.nextInt();
        BigInteger n = BigInteger.ZERO;
        for (int i = 3; i <= nth; i++) {
            n = n2.multiply(n2);
            n = n.add(n1);
            n1 = n2;
            n2 = n;
        }
       
        System.out.println(n);
    }
}

Comments

Popular posts from this blog

(Coderbyte) Dash Insert II - Solução

(Coderbyte) Run Length - Solução

(Coderbyte) Counting Minutes I - Solução