Count composite fibonacci numbers from given array - GeeksforGeeks

09 Jun, 2021
Given an array arr[] of size N, the task is to find the composite Fibonacci numbers present in the given array.
Examples:
Input: arr[] = {13, 55, 7, 3, 5, 21, 233, 144, 6}Output: 55 21 144Explanation: Composite array elements are {55, 21, 144, 6}. Fibonacci array elements are {55, 21, 144}. Therefore, array elements which are both composite as well as Fibonacci are {55, 21, 144}.
Input: arr[] = {34, 13, 11, 8, 3, 55, 233}Output: 3Explanation: Composite array elements are {34, 8, 55} Fibonacci array elements are {34, 8, 55} Therefore, array elements which are both composite as well as Fibonacci are {34, 8, 55}.
Approach: Follow the steps below to solve the problem:
Initialize a variable, say Max to store the largest element of the array.
Create a Set to store all Fibonacci numbers up to Max.
Initialize an array, say sieve[], to store all the prime numbers using Sieve Of Eratosthenes.
Finally, traverse the array and check if the current array element is both composite and Fibonacci number or not. If found to be true, then print the current element.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to find all Fibonacci// numbers up to Maxset<int> createhashmap(int Max){    // Store all Fibonacci numbers    // upto Max    set<int> hashmap;     // Stores previous element    // of Fibonacci sequence    int curr = 1;     // Stores previous element    // of Fibonacci sequence    int prev = 0;     // Insert prev into hashmap    hashmap.insert(prev);     // Insert all the Fibonacci    // numbers up to Max    while (curr <= Max) {         // Insert curr into hashmap        hashmap.insert(curr);         // Stores curr into temp        int temp = curr;         // Update curr        curr = curr + prev;         // Update prev        prev = temp;    }     return hashmap;} // Function to find all Composite// numbers up to Maxvector<bool> SieveOfEratosthenes(    int Max){     // isPrime[i]: Stores if i is    // a prime number or not    vector<bool> isPrime(Max, true);     isPrime[0] = false;    isPrime[1] = false;     // Calculate all prime numbers up to    // Max using Sieve of Eratosthenes    for (int p = 2; p * p <= Max; p++) {         // If P is a prime number        if (isPrime[p]) {             // Set all multiple of P            // as non-prime            for (int i = p * p; i <= Max;                 i += p) {                 // Update isPrime                isPrime[i] = false;            }        }    }    return isPrime;} // Function to find the numbers which is// both a composite and Fibonacci numberint cntFibonacciPrime(int arr[], int N){     // Stores the largest element    // of the array    int Max = arr[0];     // Traverse the array arr[]    for (int i = 1; i < N; i++) {         // Update Max        Max = max(Max, arr[i]);    }     // isPrim[i] check i is    // a prime number or not    vector<bool> isPrime        = SieveOfEratosthenes(Max);     // Stores all the Fibonacci numbers    set<int> hashmap        = createhashmap(Max);     // Traverse the array arr[]    for (int i = 0; i < N; i++) {         // current element is not        // a composite number        if (arr[i] == 1)            continue;         // If current element is a Fibonacci        // and composite number        if ((hashmap.count(arr[i]))            && !isPrime[arr[i]]) {             // Print current element            cout << arr[i] << " ";        }    }} // Driver Codeint main(){    int arr[] = { 13, 55, 7, 3, 5, 21,                  233, 144, 89 };    int N = sizeof(arr) / sizeof(arr[0]);     cntFibonacciPrime(arr, N);     return 0;}
// Java program to implement// the above approachimport java.util.*;class GFG{   static  boolean[] isPrime;   // Function to find all// Fibonacci numbers up// to Maxstatic HashSet<Integer>       createhashmap(int Max){  // Store all Fibonacci numbers  // upto Max  HashSet<Integer> hashmap =          new HashSet<>();   // Stores previous element  // of Fibonacci sequence  int curr = 1;   // Stores previous element  // of Fibonacci sequence  int prev = 0;   // Insert prev into hashmap  hashmap.add(prev);   // Insert all the Fibonacci  // numbers up to Max  while (curr < Max)  {    // Insert curr into    // hashmap    hashmap.add(curr);     // Stores curr into    // temp    int temp = curr;     // Update curr    curr = curr + prev;     // Update prev    prev = temp;  }   return hashmap;} // Function to find all// Composite numbers up// to Maxstatic void SieveOfEratosthenes(int Max){  // isPrime[i]: Stores if i is  // a prime number or not  isPrime = new boolean[Max];  Arrays.fill(isPrime, true);   isPrime[0] = false;  isPrime[1] = false;   // Calculate all prime numbers  // up to Max using Sieve of  // Eratosthenes  for (int p = 2;           p * p <= Max; p++)  {    // If P is a prime number    if (isPrime[p])    {      // Set all multiple of P      // as non-prime      for (int i = p * p; i <= Max;               i += p)      {           // Update isPrime        isPrime[i] = false;      }    }  }} // Function to find the numbers which is// both a composite and Fibonacci numberstatic void cntFibonacciPrime(int arr[],                              int N){  // Stores the largest element  // of the array  int Max = arr[0];   // Traverse the array arr[]  for (int i = 1; i < N; i++)  {    // Update Max    Max = Math.max(Max, arr[i]);  }   // isPrim[i] check i is  // a prime number or not  SieveOfEratosthenes(Max);   // Stores all the Fibonacci  // numbers  HashSet<Integer> hashmap =          createhashmap(Max);   // Traverse the array arr[]  for (int i = 0; i < N; i++)  {    // current element is not    // a composite number    if (arr[i] == 1)      continue;     // If current element is a    // Fibonacci and composite    // number    if ((hashmap.contains(arr[i])) &&        !isPrime[arr[i]])    {      // Print current element      System.out.print(arr[i] + " ");    }  }} // Driver Codepublic static void main(String[] args){  int arr[] = {13, 55, 7, 3, 5,               21, 233, 144, 89};  int N = arr.length;  cntFibonacciPrime(arr, N);}} // This code is contributed by Princi Singh
# Python3 program to implement# the above approachimport math # Function to find all Fibonacci# numbers up to Maxdef createhashmap(Max):         # Store all Fibonacci numbers    # upto Max    hashmap = {""}         # Stores previous element    # of Fibonacci sequence    curr = 1     # Stores previous element    # of Fibonacci sequence    prev = 0         # Insert prev into hashmap    hashmap.add(prev)         # Insert all the Fibonacci    # numbers up to Max    while (curr <= Max):                 # Insert curr into hashmap        hashmap.add(curr)                 # Stores curr into temp        temp = curr                 # Update curr        curr = curr + prev                 # Update prev        prev = temp             return hashmap # Function to find all Composite# numbers up to Maxdef SieveOfEratosthenes(Max):         # isPrime[i]: Stores if i is    # a prime number or not    isPrime = [1 for x in range(Max + 1)]    isPrime[0] = 0    isPrime[1] = 0         # Calculate all prime numbers up to    # Max using Sieve of Eratosthenes    for p in range(0, int(math.sqrt(Max))):                 # If P is a prime number        if (isPrime[p]):                         # Set all multiple of P            # as non-prime            for i in range(2 * p, Max, p):                 isPrime[i] = 0                      return isPrime # Function to find the numbers which is# both a composite and Fibonacci numberdef cntFibonacciPrime(arr, N):         # Stores the largest element    # of the array    Max = arr[0]         # Traverse the array arr[]    for i in range(0, N):                 # Update Max        Max = max(Max, arr[i])             # isPrim[i] check i is    # a prime number or not    isPrime = SieveOfEratosthenes(Max)         # Stores all the Fibonacci numbers    hashmap = createhashmap(Max)         # Traverse the array arr[]    for i in range(0, N):                 # Current element is not        # a composite number        if arr[i] == 1:            continue                 # If current element is a Fibonacci        # and composite number        if ((arr[i] in hashmap) and            (not(isPrime[arr[i]]))):                              # Print current element             print(arr[i], end = " ") # Driver Codearr = [ 13, 55, 7, 3, 5,        21, 233, 144, 89 ]N = len(arr) cntFibonacciPrime(arr, N) # This code is contributed by Stream_Cipher
// C# program to implement// the above approachusing System;using System.Collections.Generic; class GFG{   static bool[] isPrime;   // Function to find all// Fibonacci numbers up// to Maxstatic HashSet<int> createhashmap(int Max){     // Store all Fibonacci numbers  // upto Max  HashSet<int> hashmap = new HashSet<int>();     // Stores previous element  // of Fibonacci sequence  int curr = 1;   // Stores previous element  // of Fibonacci sequence  int prev = 0;   // Insert prev into hashmap  hashmap.Add(prev);   // Insert all the Fibonacci  // numbers up to Max  while (curr < Max)  {         // Insert curr into    // hashmap    hashmap.Add(curr);     // Stores curr into    // temp    int temp = curr;     // Update curr    curr = curr + prev;     // Update prev    prev = temp;  }  return hashmap;} // Function to find all// Composite numbers up// to Maxstatic void SieveOfEratosthenes(int Max){     // isPrime[i]: Stores if i is  // a prime number or not  isPrime = new bool[Max];  for(int i = 0;i<Max;i++)    isPrime[i] = true;   isPrime[0] = false;  isPrime[1] = false;   // Calculate all prime numbers  // up to Max using Sieve of  // Eratosthenes  for(int p = 2; p * p <= Max; p++)  {         // If P is a prime number    if (isPrime[p])    {             // Set all multiple of P      // as non-prime      for(int i = p * p; i <= Max;              i += p)      {                  // Update isPrime        isPrime[i] = false;      }    }  }} // Function to find the numbers which is// both a composite and Fibonacci numberstatic void cntFibonacciPrime(int []arr,                              int N){     // Stores the largest element  // of the array  int Max = arr[0];   // Traverse the array []arr  for(int i = 1; i < N; i++)  {         // Update Max    Max = Math.Max(Max, arr[i]);  }   // isPrim[i] check i is  // a prime number or not  SieveOfEratosthenes(Max);   // Stores all the Fibonacci  // numbers  HashSet<int> hashmap = createhashmap(Max);   // Traverse the array []arr  for(int i = 0; i < N; i++)  {         // current element is not    // a composite number    if (arr[i] == 1)      continue;     // If current element is a    // Fibonacci and composite    // number    if ((hashmap.Contains(arr[i])) &&        !isPrime[arr[i]])    {             // Print current element      Console.Write(arr[i] + " ");    }  }} // Driver Codepublic static void Main(String[] args){  int []arr = { 13, 55, 7, 3, 5,                21, 233, 144, 89 };  int N = arr.Length;     cntFibonacciPrime(arr, N);}} // This code is contributed by Rajput-Ji
<script> // Javascript program to implement// the above approach // Function to find all Fibonacci// numbers up to Maxfunction createhashmap(Max){         // Store all Fibonacci numbers    // upto Max    var hashmap = new Set();     // Stores previous element    // of Fibonacci sequence    var curr = 1;     // Stores previous element    // of Fibonacci sequence    var prev = 0;     // Insert prev into hashmap    hashmap.add(prev);     // Insert all the Fibonacci    // numbers up to Max    while (curr <= Max)    {                 // Insert curr into hashmap        hashmap.add(curr);         // Stores curr into temp        var temp = curr;         // Update curr        curr = curr + prev;         // Update prev        prev = temp;    }    return hashmap;} // Function to find all Composite// numbers up to Maxfunction SieveOfEratosthenes(Max){         // isPrime[i]: Stores if i is    // a prime number or not    var isPrime = Array(Max + 1).fill(true);     isPrime[0] = false;    isPrime[1] = false;     // Calculate all prime numbers up to    // Max using Sieve of Eratosthenes    for(var p = 2; p * p <= Max; p++)    {                 // If P is a prime number        if (isPrime[p])        {                         // Set all multiple of P            // as non-prime            for(var i = p * p; i <= Max;                    i += p)            {                                 // Update isPrime                isPrime[i] = false;            }        }    }    return isPrime;} // Function to find the numbers which is// both a composite and Fibonacci numberfunction cntFibonacciPrime(arr, N){         // Stores the largest element    // of the array    var Max = arr[0];     // Traverse the array arr[]    for(var i = 1; i < N; i++)    {                 // Update Max        Max = Math.max(Max, arr[i]);    }     // isPrim[i] check i is    // a prime number or not    var isPrime = SieveOfEratosthenes(Max);     // Stores all the Fibonacci numbers    var hashmap = createhashmap(Max);     // Traverse the array arr[]    for(var i = 0; i < N; i++)    {                 // current element is not        // a composite number        if (arr[i] == 1)            continue;         // If current element is a Fibonacci        // and composite number        if (hashmap.has(arr[i]) &&               !isPrime[arr[i]])        {                         // Print current element            document.write( arr[i] + " ");        }    }} // Driver Codevar arr = [ 13, 55, 7, 3, 5, 21,            233, 144, 89 ];var N = arr.length; cntFibonacciPrime(arr, N); // This code is contributed by itsok </script>
55 21 144
 
Time Complexity: O(N + Max * log(log(Max))), where Max is the largest element in the arrayAuxiliary Space: O(N)
princi singh
Rajput-Ji
Stream_Cipher
itsok
cpp-set
Fibonacci
Maths
Prime Number
sieve
Arrays
Hash
Mathematical
Searching
Arrays
Searching
Hash
Mathematical
Prime Number
Fibonacci
sieve
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Multidimensional Arrays in Java
Introduction to Arrays
Linear Search
Python | Using 2D arrays/lists the right way
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Internal Working of HashMap in Java
Hashing | Set 1 (Introduction)
Hashing | Set 3 (Open Addressing)
Count pairs with given sum