How to check if a given number is a Fibonacci number?
#include <math.h> #include <stdio.h> int isPerfectSquare(int x) { int s = sqrt(x); return (s * s == x); } int isFibonacci(int n) { return isPerfectSquare(5 * n * n + 4) || isPerfectSquare(5 * n * n - 4); } void main() { isFibonacci(4) ? printf("%d yes\n", 4) : printf("%d no\n", 4); isFibonacci(-35) ? printf("%d yes\n", -35) : printf("%d no\n", -35); isFibonacci(9227465) ? printf("%d yes\n", 9227465): printf("%d no\n", 9227465); } OUTPUT:
4 no -35 no 9227465 no online tool for checking fibonacci
This algorithm doesn't work for longer integer numbers? How to fix it to work for all possible integer numbers(range between -2147483647 -1 and 2147483647?
n?-2147483647 -1and2147483647(give or take, allowing for off-by-one error). I suggest a lookup table :)void main()is not the same asint main(). The former is wrong, and the latter is right.int main(void)would be even more right, or elseint main(int argc, char *argv[]). These two and their semantic equivalents are the only signatures that a strictly conforming C program for a hosted environment may use.