PROBLEM: IS IT FIBONACCI
The program asks you to find whether the given number is a fibonacci number or not.
Instead of generating fibonacci numbers for every query F, we can generate all fibonacci numbers till 2^64 and store it in an array FIB[].
For each query F, you can have a binary search (Since the fibonacci numbers are always in ascending order) and see if the number exists in the array.
If yes, print YES else print NO.
PSEUDOCODE:
FIB[]
def generate():
a = 0
b = 1
LIM = 2**64 ## i.e., 2^64
while a < LIM:
FIB.append(a)
c = a+b
a = b
b = c
def binarySearch(low, high, find):
while low <= high:
mid = (low+high)//2 ## integer division
if FIB[mid] == find:
return 1
elif FIB[mid] < find:
low = mid+1
else
high = mid-1
return 0
## DRIVER FUNCTION
generate()
T = int(input())
while t > 0:
f = int(input())
if binarySearch(0, len(FIB)-1, f):
print ("YES")
else
print ("NO")
t = t - 1
PROBLEM SETTER'S CODE IN C++:
#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
static const int LIM = 94;
typedef unsigned long long ull;
ull FIB[LIM];
void generate() {
ull a = 0;
ull b = 1;
ull c;
for(int i = 0; i < LIM; i++) {
FIB[i] = a;
c = a+b;
a = b;
b = c;
}
}
int main(void) {
generate();
int t;
cin >> t;
ull f;
while(t--) {
cin >> f;
bool status = binary_search(FIB, FIB+LIM, f);
if(status == false)
cout << "NO" << endl;
else
cout << "YES" << endl;
}
return 0;
}
The program asks you to find whether the given number is a fibonacci number or not.
Instead of generating fibonacci numbers for every query F, we can generate all fibonacci numbers till 2^64 and store it in an array FIB[].
For each query F, you can have a binary search (Since the fibonacci numbers are always in ascending order) and see if the number exists in the array.
If yes, print YES else print NO.
PSEUDOCODE:
FIB[]
def generate():
a = 0
b = 1
LIM = 2**64 ## i.e., 2^64
while a < LIM:
FIB.append(a)
c = a+b
a = b
b = c
def binarySearch(low, high, find):
while low <= high:
mid = (low+high)//2 ## integer division
if FIB[mid] == find:
return 1
elif FIB[mid] < find:
low = mid+1
else
high = mid-1
return 0
## DRIVER FUNCTION
generate()
T = int(input())
while t > 0:
f = int(input())
if binarySearch(0, len(FIB)-1, f):
print ("YES")
else
print ("NO")
t = t - 1
PROBLEM SETTER'S CODE IN C++:
#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
static const int LIM = 94;
typedef unsigned long long ull;
ull FIB[LIM];
void generate() {
ull a = 0;
ull b = 1;
ull c;
for(int i = 0; i < LIM; i++) {
FIB[i] = a;
c = a+b;
a = b;
b = c;
}
}
int main(void) {
generate();
int t;
cin >> t;
ull f;
while(t--) {
cin >> f;
bool status = binary_search(FIB, FIB+LIM, f);
if(status == false)
cout << "NO" << endl;
else
cout << "YES" << endl;
}
return 0;
}
No comments:
Post a Comment