Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Author : Saurav Kalsoor
- // Nearest Even Fibonacci - JAVA
- import java.util.*;
- public class Test {
- static Scanner sc = new Scanner(System.in);
- static ArrayList<Integer> list = new ArrayList<Integer>();
- public static void main(String[] args) {
- int n = sc.nextInt();
- int[] queries = new int[n];
- for(int i=0; i < n; i++) {
- queries[i] = sc.nextInt();
- }
- nearestEvenFibonacci(queries, n);
- }
- public static void init(){
- int a = 0, b = 1, c;
- list.add(a);
- list.add(b);
- int MAX_VALUE = 1000000000;
- while(a < MAX_VALUE){
- c = a + b;
- list.add(c);
- a = b;
- b = c;
- }
- }
- public static int lessThan(int n){
- int low = 0, high = list.size() - 1, index = 0;
- while(low <= high){
- int mid = low + (high - low) / 2;
- if(list.get(mid) <= n){
- index = mid;
- low = mid + 1;
- }else{
- high = mid-1;
- }
- }
- while(index >= 0 && list.get(index)%2 == 1){
- index--;
- }
- return list.get(index);
- }
- public static int greaterThan(int n){
- int low = 0, high = list.size() - 1, index = high;
- while(low <= high){
- int mid = low + (high - low) / 2;
- if(list.get(mid) >= n){
- index = mid;
- high = mid - 1;
- }else{
- low = mid + 1;
- }
- }
- while(index < list.size() && list.get(index)%2 == 1){
- index++;
- }
- return list.get(index);
- }
- public static void nearestEvenFibonacci(int[] queries,int n){
- init();
- for(int i=0; i < n; i++){
- int a = lessThan(queries[i]), b = greaterThan(queries[i]);
- int result = a;
- if(b - queries[i] <= queries[i] - a){
- result = b;
- }
- System.out.print(result + " ");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement