Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,972 questions

51,915 answers

573 users

How to get all int array elements that are fibonacci numbers in C++

1 Answer

0 votes
#include <iostream>
#include <bits/stdc++.h> 
 
using namespace std;
 
void print(unordered_set<int> const &us) {
    copy(us.begin(), us.end(), ostream_iterator<int>(cout, " "));
}
 
unordered_set<int> fibonacci_numbers(int arr[], int len) { 
    int max = *max_element(arr, arr + len); 
   
    int a = 0, b = 1; 
    unordered_set<int> fib, arr_fib; 
    fib.insert(a); 
 
    do {
        fib.insert(b); 
        int c = a + b; 
        a = b; 
        b = c; 
    } while (b <= max);
   
    for (int i = 0; i < len; i++) 
        if (fib.find(arr[i]) != fib.end()) 
            arr_fib.insert(arr[i]); 
             
    return arr_fib;
} 
   
int main() 
{ 
    // 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765
    int arr[] = {9, 1, 31, 12, 13, 3, 89, 100, 233, 4, 144, 99}; 
    int len = sizeof(arr) / sizeof(arr[0]); 
     
    unordered_set<int> arr_fib = fibonacci_numbers(arr, len); 
     
    print(arr_fib);
     
    return 0; 
} 
 
 
 
/*
run:
 
144 233 89 3 1 13 
 
*/

 



answered May 23, 2019 by avibootz
edited May 23, 2019 by avibootz
...