Advertisement
saurav_kalsoor

Nearest Even Fibonacci - JAVA

Dec 22nd, 2021
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.11 KB | None | 0 0
  1. // Author : Saurav Kalsoor
  2. // Nearest Even Fibonacci - JAVA
  3.  
  4. import java.util.*;
  5.  
  6. public class Test {
  7.  
  8.     static Scanner sc = new Scanner(System.in);
  9.     static ArrayList<Integer> list = new ArrayList<Integer>();
  10.     public static void main(String[] args) {
  11.         int n = sc.nextInt();
  12.         int[] queries = new int[n];
  13.  
  14.         for(int i=0; i < n; i++) {
  15.             queries[i] = sc.nextInt();
  16.         }
  17.  
  18.         nearestEvenFibonacci(queries, n);
  19.     }
  20.  
  21.     public static void init(){
  22.         int a = 0, b = 1, c;
  23.         list.add(a);
  24.         list.add(b);
  25.  
  26.         int MAX_VALUE = 1000000000;
  27.         while(a < MAX_VALUE){
  28.             c = a + b;
  29.             list.add(c);
  30.             a = b;
  31.             b = c;
  32.         }
  33.     }
  34.  
  35.     public static int lessThan(int n){
  36.         int low = 0, high = list.size() - 1, index = 0;
  37.         while(low <= high){
  38.             int mid = low + (high - low) / 2;
  39.             if(list.get(mid) <= n){
  40.                 index = mid;
  41.                 low = mid + 1;
  42.             }else{
  43.                 high = mid-1;
  44.             }
  45.         }
  46.  
  47.         while(index >= 0 && list.get(index)%2 == 1){
  48.             index--;
  49.         }
  50.  
  51.         return list.get(index);
  52.     }
  53.  
  54.     public static int greaterThan(int n){
  55.         int low = 0, high = list.size() - 1, index = high;
  56.         while(low <= high){
  57.             int mid = low + (high - low) / 2;
  58.             if(list.get(mid) >= n){
  59.                 index = mid;
  60.                 high = mid - 1;
  61.             }else{
  62.                 low = mid + 1;
  63.             }
  64.         }
  65.  
  66.         while(index < list.size() && list.get(index)%2 == 1){
  67.             index++;
  68.         }
  69.        
  70.         return list.get(index);
  71.     }
  72.  
  73.     public static void nearestEvenFibonacci(int[] queries,int n){
  74.         init();
  75.        
  76.         for(int i=0; i < n; i++){
  77.             int a = lessThan(queries[i]), b = greaterThan(queries[i]);
  78.             int result = a;
  79.             if(b - queries[i] <= queries[i] - a){
  80.                 result = b;
  81.             }
  82.  
  83.             System.out.print(result + " ");
  84.         }
  85.    
  86.     }
  87.  
  88. }
  89.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement