Count of distinct Primonacci Numbers in a given range [L, R]

Given two integers [L, R], the task is to count the number of Primonacci Numbers in the range [L, R]

Primonacci Series: 
F(1) = F(2) = 1 
F(3) = 3 – F(3 – 2) = F(1) = 1 
F(4) = F(4 – 2) + F(4 – 3) = F(2) + F(1) = 1 + 1 = 2 
F(5) = F(5 – 2) + F(5 – 3) = F(3) + F(2) = 1 + 1 = 2 
… 
Nth Primonacci Number, F(N) = F(N – 2) + F(N – 3) + F(N – 5) + …. + F(N – K), where K denotes the nearest prime number smaller than N 
 

Examples:  

Input: L = 1, R = 10 
Output:
Explanation: 
F(1) = 1 
F(2) = 1 
F(3) = 1 
F(4) = 2 
F(5) = 2 
F(6) = F(6 – 2) + F(6 – 3) + F(6 – 5) = F(4) + F(3) + F(1) = 2 + 1 + 1 = 4 
F(7) = F(7 – 2) + F(7 – 3) + F(7 – 5) = F(5) + F(4) + F(2) = 2 + 2 + 1 = 5 
F(8) = F(8 – 2) + F(8 – 3) + F(8 – 5) + F(8 – 7) = F(6) + F(5) + F(3) + F(1) = 4 + 2 + 1 + 1 = 8 
Therefore, distinct primonacci numbers are {1, 2, 4, 5, 8}.
Input: L = 6, R = 50 
Output:
 

Approach: 
The problem can be solved using Dynamic Programming and Sieve of Eratosthenes. Follow the steps below to solve the problem:  



  • Generate all primes using the Sieve of Eratosthenes.
  • Initialize a HashSet to store the distinct Primonacci numbers.
  • Initialize an array dp[ ], such that dp[i] stores the ith Primonacci Number.
  • Set dp[1] = dp[2] = 1.
  • For every i, iterate over all primes p, which is less than i and keep updating dp[i] by adding dp[i – p].
  • If dp[i] is within the range [L, R], insert into the HashSet.
  • Finally, if dp[i] exceeds R, print the size of the HashSet.

Below is the implementation of the above approach:

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Program to implement
// the above approach
import java.util.*;
class GFG {
 
    // Stores list of all primes
    static ArrayList<Integer> primes;
    static int M = 100005;
 
    // Function to find all primes
    static void sieve()
    {
        primes = new ArrayList<>();
 
        // To mark the prime ones
        boolean mark[] = new boolean[M];
 
        // Initially all indices as prime
        for (int i = 2; i < M; i++)
            mark[i] = true;
 
        for (int i = 2; i * i < M; i++) {
 
            // If i is prime
            if (mark[i]) {
 
                // Set all multiples
                // of i as non-prime
                for (int j = i * i;
                     j < M; j += i)
 
                    mark[j] = false;
            }
        }
 
        // Adding all primes to a list
        for (int i = 2; i < M; i++)
            if (mark[i])
                primes.add(i);
    }
 
    // Function to return the count of
    // Primonacci Numbers in the range [l, r]
    static void countPrimonacci(int l, int r)
    {
 
        // dp[i] contains ith Primonacci Number
        ArrayList<Integer> dp = new ArrayList<>();
        dp.add(1);
        dp.add(1);
        int i = 2;
 
        // Stores the Primonacci Numbers
        HashSet<Integer> s = new HashSet<>();
        while (true) {
 
            int x = 0;
 
            // Iterate over all smaller primes
            for (int j = 0; j < primes.size();
                 j++) {
 
                int p = primes.get(j);
 
                if (p >= i)
                    break;
 
                x += dp.get(i - p);
            }
 
            // If Primonacci number lies
            // within the range [L, R]
            if (x >= l && x <= r)
                s.add(x);
 
            if (x > r)
                break;
 
            dp.add(x);
            i++;
        }
 
        // Count of Primonacci Numbers
        System.out.println(s.size());
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        sieve();
 
        int L = 1, R = 10;
 
        countPrimonacci(L, R);
    }
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 implementation of
# the above approach
M = 100005
 
# Stores list of all primes
primes = []
 
# Function to find all primes
def sieve():
 
    # To mark the prime ones
    mark = [False] * M
 
    # Initially all indices as prime
    for i in range(2, M):
        mark[i] = True
 
    i = 2
    while i * i < M:
 
        # If i is prime
        if(mark[i]):
 
            # Set all multiples
            # of i as non-prime
            j = i * i
            while j < M:
                mark[j] = False
                j += i
                 
        i += 1
 
    # Adding all primes to a list
    for i in range(2, M):
        if(mark[i]):
            primes.append(i)
 
# Function to return the count of
# Primonacci Numbers in the range [l, r]
def countPrimonacci(l, r):
 
    # dp[i] contains ith Primonacci Number
    dp = []
    dp.append(1)
    dp.append(1)
    i = 2
 
    # Stores the Primonacci Numbers
    s = set()
 
    while(True):
        x = 0
 
        # Iterate over all smaller primes
        for j in range(len(primes)):
            p = primes[j]
 
            if(p >= i):
                break
 
            x += dp[i - p]
 
        # If Primonacci number lies
        # within the range [L, R]
        if(x >= l and x <= r):
            s.add(x)
 
        if(x > r):
            break
 
        dp.append(x)
        i += 1
 
    # Count of Primonacci Numbers
    print(len(s))
 
# Driver Code
if __name__ == '__main__':
 
    sieve()
    L, R = 1, 10
 
    countPrimonacci(L, R)
 
# This code is contributed by Shivam Singh

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# Program to implement
// the above approach
using System;
using System.Collections.Generic;
class GFG{
 
    // Stores list of all primes
    static List<int> primes;
    static int M = 100005;
 
    // Function to find all primes
    static void sieve()
    {
        primes = new List<int>();
 
        // To mark the prime ones
        bool[] mark = new bool[M];
 
        // Initially all indices as prime
        for (int i = 2; i < M; i++)
            mark[i] = true;
 
        for (int i = 2; i * i < M; i++)
        {
 
            // If i is prime
            if (mark[i])
            {
 
                // Set all multiples
                // of i as non-prime
                for (int j = i * i; j < M; j += i)
                    mark[j] = false;
            }
        }
 
        // Adding all primes to a list
        for (int i = 2; i < M; i++)
            if (mark[i])
                primes.Add(i);
    }
 
    // Function to return the count of
    // Primonacci Numbers in the range [l, r]
    static void countPrimonacci(int l, int r)
    {
 
        // dp[i] contains ith Primonacci Number
        List<int> dp = new List<int>();
        dp.Add(1);
        dp.Add(1);
        int i = 2;
 
        // Stores the Primonacci Numbers
        HashSet<int> s = new HashSet<int>();
        while (true)
        {
            int x = 0;
 
            // Iterate over all smaller primes
            for (int j = 0; j < primes.Count; j++)
            {
                int p = primes[j];
                if (p >= i)
                    break;
                x += dp[i - p];
            }
 
            // If Primonacci number lies
            // within the range [L, R]
            if (x >= l && x <= r)
                s.Add(x);
 
            if (x > r)
                break;
            dp.Add(x);
            i++;
        }
 
        // Count of Primonacci Numbers
        Console.WriteLine(s.Count);
    }
 
    // Driver Code
    public static void Main(String[] args)
    {
        sieve();
        int L = 1, R = 10;
        countPrimonacci(L, R);
    }
}
 
// This code is contributed by shikhasingrajput

chevron_right


Output: 

5


Time Complexity: O(N * P), where P is the count of primes up to R 
Auxiliary Space: O(N)
 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Recommended Posts:


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : shikhasingrajput