We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
- Prepare
- Mathematics
- Fundamentals
- Is Fibo
- Discussions
Is Fibo
Is Fibo
+ 0 comments JavaScript:
function isFibo(n) { // Write your code here let fibonacciSequence = [0,1]; let lastFibonacci = 1; while(lastFibonacci <= n){ if(lastFibonacci === n) return "IsFibo"; fibonacciSequence.push(lastFibonacci); lastFibonacci = fibonacciSequence.at(-2) + fibonacciSequence.at(-1); } return "IsNotFibo"; }
+ 0 comments def isFibo(n): # Write your code here start = 0 last = 1 while last <= n: tmp = last + start start = last last = tmp if last== n: return "IsFibo" return "IsNotFibo"
+ 0 comments def checkSquare(value): return int(sqrt(value))**2 == value def isFibo(n): if checkSquare(5*n**2 + 4) == True or checkSquare(5*n**2-4) == True : return "IsFibo" else: return "IsNotFibo"
+ 0 comments a,b = 0,1 while b < n : a,b=b,a+b if b == n : return ("IsFibo") else: return ("IsNotFibo")
+ 0 comments I think I overengineerd my solution by constructing a perfect hashset, there are after all only 49 fibonacci numbers below 10 billion. Here is my C solution:
#include <stdlib.h> #include <stdio.h> #include <string.h> // A nice prime number #define NUM_BUCKETS 137 // A magic number that removes all collisions. Found by random search #define MAGIC_NUMBER 1428417140 size_t hash_set[NUM_BUCKETS]; size_t hash_function(size_t number) { return (number ^ (number << 17) ^ MAGIC_NUMBER) % NUM_BUCKETS; } void initialzie() { size_t previous_previous_fibonacci_number = 0; size_t previous_fibonacci_number = 1; size_t index = 0; memset(hash_set, 0, NUM_BUCKETS*sizeof(size_t)); while (previous_fibonacci_number <= 10000000000) { size_t fibonacci_number = previous_fibonacci_number + previous_previous_fibonacci_number; previous_previous_fibonacci_number = previous_fibonacci_number; previous_fibonacci_number = fibonacci_number; hash_set[hash_function(fibonacci_number)] = fibonacci_number; } } int is_fibonacci(size_t candidate) { return hash_set[hash_function(candidate)] == candidate; } int main() { initialzie(); size_t num_test_cases = 0; scanf("%lu", &num_test_cases); for (size_t i = 0; i < num_test_cases; i++) { size_t number = 0; scanf("%lu", &number); printf("Is%sFibo\n", is_fibonacci(number) ? "" : "Not"); } }
Load more conversations
Sort 379 Discussions, By:
Please Login in order to post a comment