Monday, August 14, 2017

Reverse Fibonacci series from given first two numbers

Case-1: If the first two numbers at the high end is given, then use the code below:

import java.util.*;
import java.io.*;

public class ReverseFibonacci {

    public static void main(String a[]){
     
     
         //int[] feb = new int[10];
         ArrayList<Integer> feb = new ArrayList<Integer>();
         feb.add(80);  // last number
         feb.add(50); // second from the last number
         for(int i=2; feb.get(i-2)-feb.get(i-1)>=0 && feb.get(i-1) != 0; ++i){
             if(feb.get(i-2)-feb.get(i-1) <= feb.get(i-1))
                feb.add(feb.get(i-2) - feb.get(i-1));
             else if (feb.get(i-2)-feb.get(i-1) >= feb.get(i-1)) {
                feb.add(feb.get(i-1));
             }
         }

         for(int i=0; i< feb.size(); i++){
                 System.out.print(feb.get(i) + " ");
         }
    }
}

Output: 80 50 30 20 10 10 0


Case - 2: If the starting two numbers are given then use the code below:

import java.util.*;
import java.io.*;

public class MyFibonacci {

    public static void main(String a[]){
       
       
         //int[] feb = new int[10];
         ArrayList<Integer> feb = new ArrayList<Integer>();
         feb.add(5); // starting number
         feb.add(15); // second given number
         for(int i=2; i<=6; ++i){
             feb.add(feb.get(i-2) + feb.get(i-1));
         }

         for(int i=feb.size()-1; i >= 0; i--){
                 System.out.print(feb.get(i) + " ");
         }
    }
}

Output: 80 50 30 20 10 10 0

No comments:

Post a Comment

My Journey from a Tier-3 College to Microsoft, Google, and Meta: Lessons Learned

Original post: Link   Time to give back to community. Went through couple of post myself and got inspired and belief that cracking FAANG is ...