Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Author : Saurav Kalsoor
- // Nearest Even Fibonacci - KOTLIN
- import java.util.*
- var sc: Scanner = Scanner(System.`in`)
- var list: ArrayList<Int> = ArrayList<Int>()
- fun main() {
- val n: Int = sc.nextInt()
- val queries = IntArray(n)
- for (i in 0 until n) {
- queries[i] = sc.nextInt()
- }
- nearestEvenFibonacci(queries, n)
- }
- fun init() {
- var a = 0
- var b = 1
- var c: Int
- list.add(a)
- list.add(b)
- val MAX_VALUE = 1000000000
- while (a < MAX_VALUE) {
- c = a + b
- list.add(c)
- a = b
- b = c
- }
- }
- fun lessThan(n: Int): Int {
- var low = 0
- var high: Int = list.size - 1
- var index = 0
- while (low <= high) {
- val 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)
- }
- fun greaterThan(n: Int): Int {
- var low = 0
- var high: Int = list.size - 1
- var index = high
- while (low <= high) {
- val 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)
- }
- fun nearestEvenFibonacci(queries: IntArray, n: Int) {
- init()
- for (i in 0 until n) {
- val a = lessThan(queries[i])
- val b = greaterThan(queries[i])
- var result = a
- if (b - queries[i] <= queries[i] - a) {
- result = b
- }
- print("$result ")
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement