Hackerrank "Is Fibo" challenge solution in Python 3

N is a fibonacci number if and only 5N^2 + 4 or 5N^2 – 4 is a perfect square number http://en.wikipedia.org/wiki/Fibonacci_number#Recognizing_Fibonacci_numbers

Solution in python 3:

import math

n = int(input())
for i in range(0,n):
    number = int(input())
    if math.sqrt(5 * number ** 2 + 4).is_integer() or math.sqrt(5 * number ** 2 - 4).is_integer():
        print("IsFibo")
    else:
        print("IsNotFibo")

This solution has a complexity O(1) compared to simple solution by adding all numbers from 0 to N that has a O(n) complexity

Comments

Popular posts from this blog

Memory efficient array permutation in PHP 5.5 using generators

How to dump http request headers with PHP under CGI/FastCGI SAPI

Zend Framework 2 AJAX: return JSON response from controller action. The proper way.