Summary:
Suppose we have a positive integer n and we have to find the nth fibonacci number.
Solution:
//User function Template for Java //User function Template for Java class Solution { static int nthFibonacci(int n){ // code here ArrayList<Integer> arr=new ArrayList<>(); int mod = 1000000007; arr.add(0); arr.add(1); if(n==1){ return 1; } else{ for(int i=2;i<=n;i++){ int j=(arr.get(i-2)+arr.get(i-1))%mod; arr.add(j); } return arr.get(n); } } } |
Explanation:
This above written Java code defines a function nthFibonacci that calculates the nth Fibonacci number modulo 10^9 + 7. It iteratively computes Fibonacci numbers up to the nth number and stores them in an ArrayList for efficiency. Finally, it returns the nth Fibonacci number.
Answered by: >21r01a0528
Credit: >GeekforGeeks
Suggested blogs:
>Python Error Solved: load_associated_files do not load a txt file
>Python Error Solved: pg_config executable not found
>Set up Node.js & connect to a MongoDB Database Using Node.js
>Setting up a Cloud Composer environment: Step-by-step guide
>What is microservice architecture, and why is it better than monolithic architecture?
>What makes Python 'flow' with HTML nicely as compared to PHP?
>What to do when MQTT terminates an infinite loop while subscribing to a topic in Python?
>Creating custom required rule - Laravel validation
>How to configure transfers for different accounts in stripe with laravel?