 GeeksforGeeks App
Open App Browser
Continue

# Prime Fibonacci | TCS Mockvita 2020

#### Problem Description

Given two numbers N1 and N2.

1. Find prime numbers between N1 and N2, then
2. Make all possible unique combinations of numbers from the list of the prime numbers you found in step 1.
3. From this new list, again find all prime numbers.
4. Find smallest A and largest B number from the 2nd generated list, also count of this list.
5. Consider smallest and largest number as the 1st and 2nd number to generate Fibonacci series respectively till the count (Number of primes in the 2nd list).
6. Print the last number of a Fibonacci series as an output

Constraints

2 <= N1, N2 <= 100

N2 – N1 >= 35

Examples:

Input:  N1 = 2, N2 = 40
Output: 13158006689
Explanation:
First prime list = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]

Combination of all the primes = [23, 25, 27, 211, 213, 217, 219, 223, 229, 231, 32, 35, 37, 311, 313, 319, 323, 329, 331, 337, 52, 53, 57, 511, 513, 517, 519, 523, 529, 531, 537, 72, 73, 75, 711, 713, 717, 719, 723, 729, 731, 737, 112, 113, 115, 117, 1113, 1117, 1119, 1123, 1129, 1131, 1137, 132, 133, 135, 137, 1311, 1317, 1319, 1323, 1329, 1331, 1337, 172, 173, 175, 177, 1711, 1713, 1719, 1723, 1729, 1731, 1737, 192, 193, 195, 197, 1911, 1913, 1917, 1923, 1929, 1931, 1937, 232, 233, 235, 237, 2311, 2313, 2317, 2319, 2329, 2331, 2337, 292, 293, 295, 297, 2911, 2913, 2917, 2919, 2923, 2931, 2937, 312, 315, 317, 3111, 3113, 3117, 3119, 3123, 3129, 3137, 372, 373, 375, 377, 3711, 3713, 3717, 3719, 3723, 3729, 3731]

Second prime list=[193, 3137, 197, 2311, 3719, 73, 137, 331, 523, 1931, 719, 337, 211, 23, 1117, 223, 1123, 229, 37, 293, 2917, 1319, 1129, 233, 173, 3119, 113, 53, 373, 311, 313, 1913, 1723, 317]

smallest (A) = 23

largest (B) = 3719
Therefore, the last number of a Fibonacci series i.e. 34th Fibonacci number in the series that has 23 and 3719 as the first 2 numbers is 13158006689

Input: N1 = 30, N2 = 70
Output: 2027041
Explanation:

First prime list = [31, 37, 41, 43, 47, 53, 59, 61, 67]

Second prime list generated form combination of 1st prime list = [3137, 5953, 5347, 6761, 3761, 4337, 6737, 6131, 3767, 4759, 4153, 3167, 4159, 6143]
Smallest prime in 2nd list=3137
Largest prime in 2nd list=6761
Therefore, the last number of a Fibonacci series i.e. 14th Fibonacci number in the series that has 3137 and 6761 as the first 2 numbers is 2027041

Approach: The idea is to use Sieve of Eratosthenes to check that a particular number is a prime number or not in O(1) time. Therefore, Iterate over all the numbers from N1 to N2 and store all the prime numbers in that range in an array, and then using Nested Loop find all unique possible combinations of the prime numbers. Finally, find the prime numbers from all the combination and then the minimum and the maximum of those prime numbers. Using the minimum and the maximum prime numbers we can generate the Fibonacci series to compute the last term (Number of prime numbers in all the combinations) of the Fibonacci series.

Below is the implementation of the above approach:

## C++

 `// C++ implementation to compute the``// combination of every possible``// prime numbers of the range` `#include ``using` `namespace` `std;` `long` `long` `maxN = 1e5;` `// Sieve of Eratosthenes``void` `sieve(vector<``bool``>& primes)``{``    ``for` `(``long` `long` `num = 2;``         ``num * num < maxN; num++) {``        ``if` `(primes[num]) {``            ``for` `(``long` `long` `i = num * num;``                       ``i < maxN; i += num)``                ``primes[i] = ``false``;``        ``}``    ``}``}` `// Function to find the Nth term of``// of the Fibonacci series``long` `long` `solve(``long` `long` `N1,``                ``long` `long` `N2)``{``    ``vector<``bool``> primes(maxN, ``true``);``    ``// 1 in not prime``    ``primes = ``false``;``    ``// generate all prime in range``    ``// using sieve of eratosthenes``    ``sieve(primes);` `    ``vector filteredPrimes;``    ``vector<``long` `long``> comb;``    ``set<``long` `long``> lst;` `    ``// filter required primes and``    ``// put them into filteredPrimes``    ``// as strings``    ``for` `(``long` `long` `i = N1; i <= N2; i++)``        ``if` `(primes[i])``            ``filteredPrimes.push_back(``                          ``to_string(i));` `    ``// make all possible combinations``    ``for` `(``long` `long` `i = 0;``         ``i < (``long` `long``)(filteredPrimes.size());``                                        ``i++) {``        ``for` `(``long` `long` `j = 0;``             ``j < (``long` `long``)(filteredPrimes.size());``                                        ``j++) {``            ``if` `(i == j)``                ``continue``;` `            ``string tmp = filteredPrimes[i] +``                         ``filteredPrimes[j];``            ``comb.push_back(stoi(tmp));``        ``}``    ``}` `    ``// Filter only prime numbers``    ``// for generated combinations``    ``for` `(``long` `long` `x : comb)``        ``if` `(primes[x])``            ``lst.insert(x);` `    ``auto` `it = lst.end();``    ``it--;``  ` `    ``// take smallest and largest element``    ``long` `long` `a = *(lst.begin()), b = *it, c;` `    ``// Now find last element``    ``// of fibonacci series``    ``for` `(``long` `long` `i = 3;``         ``i <= (``long` `long``)(lst.size());``                                 ``i++) {``        ``c = a + b;``        ``a = b;``        ``b = c;``    ``}` `    ``return` `c;``}` `// Driver Code``int` `main()``{``    ``long` `long` `N1 = 2, N2 = 40;` `    ``cout << solve(N1, N2);` `    ``return` `0;``}`

## Java

 `// Java implementation to compute the``// combination of every possible``// prime numbers of the range``import` `java.util.*;``import` `java.util.stream.*;` `class` `GFG``{``  ``static` `long` `maxN = ``100000``;` `  ``// Sieve of Eratosthenes``  ``static`  `void` `sieve(ArrayList primes)``  ``{``    ``for` `(``long` `num = ``2``;``         ``num * num < maxN; num++) {``      ``if` `(primes.get((``int``)num)) {``        ``for` `(``long` `i = num * num;``             ``i < maxN; i += num)``          ``primes.set((``int``)i, ``false``);``      ``}``    ``}``  ``}` `  ``// Function to find the Nth term of``  ``// of the Fibonacci series``  ``static` `long` `solve(``long` `N1,``                    ``long` `N2)``  ``{``    ``ArrayList primes = ``new` `ArrayList();` `    ``for` `(``int` `i = ``0``; i < (``int``)maxN; i++)``      ``primes.add(``true``);` `    ``// 1 in not prime``    ``primes.set(``1``, ``false``);``    ` `    ``// generate all prime in range``    ``// using sieve of eratosthenes``    ``sieve(primes);` `    ``ArrayList filteredPrimes = ``new` `ArrayList();``    ``ArrayList comb = ``new` `ArrayList();``    ``HashSet lst = ``new` `HashSet();` `    ``long` `c = ``0``;``    ``// filter required primes and``    ``// put them into filteredPrimes``    ``// as strings``    ``for` `(``long` `i = N1; i <= N2; i++)``      ``if` `(primes.get((``int``)i))``        ``filteredPrimes.add(String.valueOf(i));` `    ``// make all possible combinations``    ``for` `(``long` `i = ``0``;``         ``i < (``long``)(filteredPrimes.size());``         ``i++) {``      ``for` `(``long` `j = ``0``;``           ``j < (``long``)(filteredPrimes.size());``           ``j++) {``        ``if` `(i == j)``          ``continue``;` `        ``String tmp = filteredPrimes.get((``int``)i) +``          ``filteredPrimes.get((``int``)j);``        ``comb.add(Long.valueOf(tmp));``      ``}``    ``}` `    ``// Filter only prime numbers``    ``// for generated combinations``    ``for` `(``long` `x : comb)``      ``if` `(primes.get((``int``)x))``        ``lst.add(x);`   `    ``Iterator it = lst.iterator();` `    ``long``[] lst1 =  ``new` `long``[lst.size()];``    ``int` `i = ``0``;``    ``while` `(it.hasNext())``      ``lst1[i++] = it.next();` `    ``Arrays.sort(lst1);` `    ``// take smallest and largest element``    ``long` `a = ``0``;``    ``long` `b =  lst1[lst1.length - ``1``];` `    ``// Now find last element``    ``// of fibonacci series``    ``for` `(``long` `j = ``3``;``         ``j <= (``long``)(lst.size());``         ``j++) {``      ``c = a + b;``      ``a = b;``      ``b = c;``    ``}` `    ``return` `c;``  ``}` `  ``// Driver Code``  ``public` `static` `void` `main(String[] args)``  ``{``    ``long` `N1 = ``2``, N2 = ``40``;` `    ``System.out.println(solve(N1, N2));``  ``}``}` `// This code is contributed by phasing17`

## Python3

 `# Python3 implementation to compute the``# combination of every possible``# prime numbers of the range``maxN ``=` `100000``;` `# Sieve of Eratosthenes``def` `sieve(primes):``    ` `    ``for` `num ``in` `range``(``2``, ``int``(maxN ``*``*` `0.5``) ``+` `1``):``        ``if` `(primes[num]):``            ``for` `i ``in` `range``(num ``*` `num, maxN, num):``                ``primes[i] ``=` `False``;``            ` `# Function to find the Nth term of``# of the Fibonacci series``def` `solve(N1, N2):``    ` `    ``primes ``=` `[``True` `for` `_ ``in` `range``(maxN)]` `    ``# 1 in not prime``    ``primes[``1``] ``=` `False``;``    ` `    ``# generate all prime in range``    ``# using sieve of eratosthenes``    ``sieve(primes);` `    ``filteredPrimes ``=` `[]``    ``comb ``=` `[]``    ``lst ``=` `set``()` `    ``# filter required primes and``    ``# put them into filteredPrimes``    ``# as strings``    ``for` `i ``in` `range``(N1, N2 ``+` `1``):``        ``if` `(primes[i]):``            ``filteredPrimes.append(``str``(i))`  `    ``# make all possible combinations``    ``for` `i ``in` `range``(``len``(filteredPrimes)):``        ``for` `j ``in` `range``(``len``(filteredPrimes)):``            ``if` `(i ``=``=` `j):``                ``continue``;` `            ``tmp ``=` `filteredPrimes[i] ``+` `filteredPrimes[j];``            ``comb.append(``int``(tmp));``        ` `    ``# Filter only prime numbers``    ``# for generated combinations``    ``for` `i ``in` `range``(``len``(comb)):``        ``if``(primes[comb[i]]):``            ``lst.add(comb[i]);``        ` `    ``# take smallest and largest element``    ``a ``=` `sorted``(lst)[``0``]``    ``b ``=` `sorted``(lst)[``-``1``]``    ``c ``=` `0``;` `    ``# Now find last element``    ``# of fibonacci series``    ``for` `i ``in` `range``(``3``, ``len``(lst) ``+` `1``):``        ``c ``=` `a ``+` `b;``        ``a ``=` `b;``        ``b ``=` `c;``    ` `    ``return` `c;` `# Driver Code``N1 ``=` `2``;``N2 ``=` `40``;``print``(solve(N1, N2));` `# The code is contributed by phasing17`

## C#

 `// C# implementation to compute the``// combination of every possible``// prime numbers of the range``using` `System;``using` `System.Linq;``using` `System.Collections.Generic;` `class` `GFG``{``  ``static` `long` `maxN = 100000;` `  ``// Sieve of Eratosthenes``  ``static`  `void` `sieve(List<``bool``> primes)``  ``{``    ``for` `(``long` `num = 2;``         ``num * num < maxN; num++) {``      ``if` `(primes[(``int``)num]) {``        ``for` `(``long` `i = num * num;``             ``i < maxN; i += num)``          ``primes[(``int``)i] = ``false``;``      ``}``    ``}``  ``}` `  ``// Function to find the Nth term of``  ``// of the Fibonacci series``  ``static` `long` `solve(``long` `N1,``                    ``long` `N2)``  ``{``    ``List<``bool``> primes = ``new` `List<``bool``>();` `    ``for` `(``int` `i = 0; i < (``int``)maxN; i++)``      ``primes.Add(``true``);` `    ``// 1 in not prime``    ``primes = ``false``;``    ``// generate all prime in range``    ``// using sieve of eratosthenes``    ``sieve(primes);` `    ``List<``string``> filteredPrimes = ``new` `List<``string``>();``    ``List<``long``> comb = ``new` `List<``long``>();``    ``HashSet<``long``> lst = ``new` `HashSet<``long``>();` `    ``long` `c = 0;``    ``// filter required primes and``    ``// put them into filteredPrimes``    ``// as strings``    ``for` `(``long` `i = N1; i <= N2; i++)``      ``if` `(primes[(``int``)i])``        ``filteredPrimes.Add(Convert.ToString(i));` `    ``// make all possible combinations``    ``for` `(``long` `i = 0;``         ``i < (``long``)(filteredPrimes.Count);``         ``i++) {``      ``for` `(``long` `j = 0;``           ``j < (``long``)(filteredPrimes.Count);``           ``j++) {``        ``if` `(i == j)``          ``continue``;` `        ``string` `tmp = filteredPrimes[(``int``)i] +``          ``filteredPrimes[(``int``)j];``        ``comb.Add(Convert.ToInt32(tmp));``      ``}``    ``}` `    ``// Filter only prime numbers``    ``// for generated combinations``    ``foreach` `(``long` `x ``in` `comb)``      ``if` `(primes[(``int``)x])``        ``lst.Add(x);` `    ``var` `it = lst.Count;``    ``it--;` `    ``long``[] lst1 = lst.ToArray();` `    ``// take smallest and largest element``    ``long` `a = 0;``    ``long` `b = lst1.Max();` `    ``// Now find last element``    ``// of fibonacci series``    ``for` `(``long` `i = 3;``         ``i <= (``long``)(lst.Count);``         ``i++) {``      ``c = a + b;``      ``a = b;``      ``b = c;``    ``}` `    ``return` `c;``  ``}` `  ``// Driver Code``  ``public` `static` `void` `Main(``string``[] args)``  ``{``    ``long` `N1 = 2, N2 = 40;` `    ``Console.WriteLine(solve(N1, N2));``  ``}``}` `// This code is contributed by phasing17`

## Javascript

 `// JavaScript implementation to compute the``// combination of every possible``// prime numbers of the range` `const maxN = 1e5;` `// Sieve of Eratosthenes``function` `sieve(primes)``{``    ``for` `(let num = 2; num * num < maxN; num++) {``        ``if` `(primes[num] == ``true``) {``            ``for` `(let i = num * num; i < maxN; i += num){``                ``primes[i] = ``false``;``            ``}``        ``}``    ``}``}` `// Function to find the Nth term of``// of the Fibonacci series``function` `solve(N1, N2)``{``    ``let primes = ``new` `Array(maxN).fill(``true``);``    ` `    ``// 1 in not prime``    ``primes = ``false``;``    ` `    ``// generate all prime in range``    ``// using sieve of eratosthenes``    ``sieve(primes);` `    ``let filteredPrimes = ``new` `Array();``    ``let comb = ``new` `Array();``    ``let lst = ``new` `Set();` `    ``// filter required primes and``    ``// put them into filteredPrimes``    ``// as strings``    ``for` `(let i = N1; i <= N2; i++)``        ``if` `(primes[i] == ``true``)``            ``filteredPrimes.push(i.toString());`  `    ``// make all possible combinations``    ``for` `(let i = 0; i < filteredPrimes.length; i++) {``        ``for` `(let j = 0; j < filteredPrimes.length; j++) {``            ``if` `(i == j)``                ``continue``;` `            ``let tmp = filteredPrimes[i] + filteredPrimes[j];``            ``comb.push(parseInt(tmp));``        ``}``    ``}``    ` `    ``// Filter only prime numbers``    ``// for generated combinations``    ``for``(let i = 0; i < comb.length; i++){``        ``if``(primes[comb[i]] == ``true``){``            ``lst.add(comb[i]);``        ``}``    ``}``    ` `    ``// take smallest and largest element``    ``let a = [...lst].sort(``function``(a, b){``return` `a-b});``    ``let b = [...lst].sort(``function``(a, b){``return` `a-b})[lst.size - 1];``    ``let c = 0;` `    ``// Now find last element``    ``// of fibonacci series``    ``for` `(let i = 3; i <= lst.size; i++) {``        ``c = a + b;``        ``a = b;``        ``b = c;``    ``}` `    ``return` `c;``}` `// Driver Code``let N1 = 2;``let N2 = 40;``console.log(solve(N1, N2));` `// The code is contributed by Gautam goel (gautamgoel962)`

Output

`13158006689`

Time Complexity: O( maxN × log(log(maxN)))
Auxiliary Space: O(maxN)

My Personal Notes arrow_drop_up