Hackerrank – Is Fibo
Popis problému Celý popis zadania sa nacháza – Hackerrank. Riešenie Vytvoríme si Fibonacciho postupnosť a zistíme, či sa fibonaciho číslo rovná požadovanému n. Vytvoril som riešenie v týchto programovacích jazykoch: Java JavaScript Scala Ruby Všetky riešenia sú dostupné aj na mojom GitHub profile. Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
import java.math.BigInteger; import java.util.*; public class IsFibo { public static void main(String[] args) { Scanner stdin = new Scanner(System.in); int tests = stdin.nextInt(); for(int i = 0; i < tests; i++) { BigInteger n = stdin.nextBigInteger(); System.out.println(isFibo(n)); } stdin.close(); } private static String isFibo(BigInteger n) { BigInteger fib0 = BigInteger.ZERO; BigInteger fib1 = BigInteger.ONE; while(fib0.compareTo(n) <= 0) { if (fib0.compareTo(n) == 0) return "IsFibo"; BigInteger temp = fib0; fib0 = fib1; fib1 = fib1.add(temp); } return "IsNotFibo"; } } |
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
'use strict'; let isFibo = n => { let fib0 = 0; let fib1 = 1; while(fib0 <= n) { if (fib0 == n) return "IsFibo"; let temp = fib0; fib0 = fib1; fib1 += temp; } return "IsNotFibo" }; const processData = input => { console.log(input.split("\n").slice(1).map(i => parseInt(i)).map(isFibo).join("\n")); }; process.stdin.resume(); process.stdin.setEncoding("ascii"); var _input = ""; process.stdin.on("data", input => _input += input); process.stdin.on("end", () => processData(_input)); |
Scala
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import scala.io.Source object IsFibo extends App { val lines = Source.stdin.getLines() val numbers = lines.drop(1).map(BigInt(_)) val fibos = numbers.map(isFibo) println(fibos.mkString("\n")) def isFibo(n: BigInt): String = { var fib0: BigInt = 0 var fib1: BigInt = 1 while(fib0 <= n) { if (fib0 == n) return "IsFibo" val temp: BigInt = fib0 fib0 = fib1 fib1 += temp } "IsNotFibo" } } |
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
def is_fibo(number) fib0 = 0 fib1 = 1 while fib0 <= number do return "IsFibo" if fib0 == number temp = fib0 fib0 = fib1 fib1 += temp end return "IsNotFibo" end test_cases = gets.chomp.to_i test_cases.times do number = gets.chomp.to_i result = is_fibo(number) puts result end |