Advertisement
saurav_kalsoor

Nearest Even Fibonacci - KOTLIN

Dec 22nd, 2021
197
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.75 KB | None | 0 0
  1. // Author : Saurav Kalsoor
  2. // Nearest Even Fibonacci - KOTLIN
  3.  
  4. import java.util.*
  5.  
  6.  
  7. var sc: Scanner = Scanner(System.`in`)
  8. var list: ArrayList<Int> = ArrayList<Int>()
  9.  
  10.  
  11. fun main() {
  12.     val n: Int = sc.nextInt()
  13.     val queries = IntArray(n)
  14.     for (i in 0 until n) {
  15.         queries[i] = sc.nextInt()
  16.     }
  17.     nearestEvenFibonacci(queries, n)
  18. }
  19.  
  20. fun init() {
  21.     var a = 0
  22.     var b = 1
  23.     var c: Int
  24.     list.add(a)
  25.     list.add(b)
  26.     val 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. fun lessThan(n: Int): Int {
  36.     var low = 0
  37.     var high: Int = list.size - 1
  38.     var index = 0
  39.     while (low <= high) {
  40.         val mid = low + (high - low) / 2
  41.         if (list.get(mid) <= n) {
  42.             index = mid
  43.             low = mid + 1
  44.         } else {
  45.             high = mid - 1
  46.         }
  47.     }
  48.     while (index >= 0 && list.get(index) % 2 == 1) {
  49.         index--
  50.     }
  51.     return list.get(index)
  52. }
  53.  
  54. fun greaterThan(n: Int): Int {
  55.     var low = 0
  56.     var high: Int = list.size - 1
  57.     var index = high
  58.     while (low <= high) {
  59.         val mid = low + (high - low) / 2
  60.         if (list.get(mid) >= n) {
  61.             index = mid
  62.             high = mid - 1
  63.         } else {
  64.             low = mid + 1
  65.         }
  66.     }
  67.     while (index < list.size && list.get(index) % 2 == 1) {
  68.         index++
  69.     }
  70.     return list.get(index)
  71. }
  72.  
  73. fun nearestEvenFibonacci(queries: IntArray, n: Int) {
  74.     init()
  75.     for (i in 0 until n) {
  76.         val a = lessThan(queries[i])
  77.         val b = greaterThan(queries[i])
  78.         var result = a
  79.         if (b - queries[i] <= queries[i] - a) {
  80.             result = b
  81.         }
  82.         print("$result ")
  83.     }
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement