Open In App

Ramanujan Prime

Last Updated : 31 May, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

The Nth Ramanujan prime is the least integer Rn for which
 

 

where ?(x) is a prime-counting function
Note that the integer Rn is necessarily a prime number: ?(x) – ?(x/2) and, hence, ?(x) must increase by obtaining another prime at x = Rn. Since ?(x) – ?(x/2) can increase by at most 1, 
Range of Rn is (2n log(2n), 4n log(4n)).
 

 

Ramanujan primes: 
 

2, 11, 17, 29, 41, 47, 59, 67, 71, 97 
 

For a given N, the task is to print first N Ramanujan primes
Examples: 
 

Input : N = 5 
Output : 2, 11, 17, 29, 41
Input : N = 10 
Output : 2, 11, 17, 29, 41, 47, 59, 67, 71, 97 
 

 

Approach: 
Let us divide our solution into parts, 
First, we will use sieve of Eratosthenes to get all the primes less than 10^6
Now we will have to find the value of ?(x), ?(x) is the count of primes which are less than or equal to x. Primes are stored in increasing order. So we can perform a binary search to find all the primes less than x, which can be done in O(log n)
Now we have the range Rn lies between : 2n log(2n) < Rn < 4n log(4n) So, we will take the upper bound and iterate from upper bound to the lower bound until ?(i) – ?(i/2) < n, i+1 is the nth Ramanujan prime.
Below is the implementation of the above approach : 
 

C++




// CPP program to find Ramanujan numbers
#include <bits/stdc++.h>
using namespace std;
#define MAX 1000000
 
// FUnction to return a vector of primes
vector<int> addPrimes()
{
    int n = MAX;
 
    // Create a boolean array "prime[0..n]" and initialize
    // all entries it as true. A value in prime[i] will
    // finally be false if i is Not a prime, else true.
    bool prime[n + 1];
    memset(prime, true, sizeof(prime));
 
    for (int p = 2; p * p <= n; p++)
    {
        // If prime[p] is not changed, then it is a prime
        if (prime[p] == true)
        {
            // Update all multiples of p greater than or
            // equal to the square of it
            // numbers which are multiple of p and are
            // less than p^2 are already been marked.
            for (int i = p * p; i <= n; i += p)
                prime[i] = false;
        }
    }
 
    vector<int> ans;
    // Print all prime numbers
    for (int p = 2; p <= n; p++)
        if (prime[p])
            ans.push_back(p);
 
    return ans;
}
// Function to find number of primes
// less than or equal to x
int pi(int x, vector<int> v)
{
    int l = 0, r = v.size() - 1, m, in = -1;
 
    // Binary search to find out number of
    // primes less than or equal to x
    while (l <= r) {
        m = (l + r) / 2;
        if (v[m] <= x) {
            in = m;
            l = m + 1;
        }
        else {
            r = m - 1;
        }
    }
    return in + 1;
}
 
// Function to find the nth ramanujan prime
int Ramanujan(int n, vector<int> v)
{
    // For n>=1, a(n)<4*n*log(4n)
    int upperbound = 4 * n * (log(4 * n) / log(2));
 
    // We start from upperbound and find where
    // pi(i)-pi(i/2)<n the previous number being
    // the nth ramanujan prime
    for (int i = upperbound;; i--) {
        if (pi(i, v) - pi(i / 2, v) < n)
            return 1 + i;
    }
}
 
// Function to find first n Ramanujan numbers
void Ramanujan_Numbers(int n)
{
    int c = 1;
 
    // Get the prime numbers
    vector<int> v = addPrimes();
 
    for (int i = 1; i <= n; i++) {
        cout << Ramanujan(i, v);
        if(i!=n)
            cout << ", ";
    }
}
 
// Driver code
int main()
{
    int n = 10;
 
    Ramanujan_Numbers(n);
 
    return 0;
}


Java




// Java program to find Ramanujan numbers
import java.util.*;
class GFG
{
     
static int MAX = 1000000;
 
// FUnction to return a vector of primes
static Vector<Integer> addPrimes()
{
    int n = MAX;
 
    // Create a boolean array "prime[0..n]" and
    // initialize all entries it as true.
    // A value in prime[i] will finally be false
    // if i is Not a prime, else true.
    boolean []prime= new boolean[n + 1];
    Arrays.fill(prime, true);
 
    for (int p = 2; p * p <= n; p++)
    {
        // If prime[p] is not changed,
        // then it is a prime
        if (prime[p] == true)
        {
            // Update all multiples of p greater than or
            // equal to the square of it
            // numbers which are multiple of p and are
            // less than p^2 are already been marked.
            for (int i = p * p; i <= n; i += p)
                prime[i] = false;
        }
    }
 
    Vector<Integer> ans = new Vector<Integer>();
     
    // Print all prime numbers
    for (int p = 2; p <= n; p++)
        if (prime[p])
            ans.add(p);
 
    return ans;
}
 
// Function to find number of primes
// less than or equal to x
static int pi(int x, Vector<Integer> v)
{
    int l = 0, r = v.size() - 1, m, in = -1;
 
    // Binary search to find out number of
    // primes less than or equal to x
    while (l <= r)
    {
        m = (l + r) / 2;
        if (v.get(m) <= x)
        {
            in = m;
            l = m + 1;
        }
        else
        {
            r = m - 1;
        }
    }
    return in + 1;
}
 
// Function to find the nth ramanujan prime
static int Ramanujan(int n, Vector<Integer> v)
{
    // For n>=1, a(n)<4*n*log(4n)
    int upperbound = (int) (4 * n * (Math.log(4 * n) /
                                     Math.log(2)));
 
    // We start from upperbound and find where
    // pi(i)-pi(i/2)<n the previous number being
    // the nth ramanujan prime
    for (int i = upperbound;; i--)
    {
        if (pi(i, v) - pi(i / 2, v) < n)
            return 1 + i;
    }
}
 
// Function to find first n Ramanujan numbers
static void Ramanujan_Numbers(int n)
{
    int c = 1;
 
    // Get the prime numbers
    Vector<Integer> v = addPrimes();
 
    for (int i = 1; i <= n; i++)
    {
        System.out.print(Ramanujan(i, v));
        if(i != n)
            System.out.print(", ");
    }
}
 
// Driver code
public static void main(String[] args)
{
    int n = 10;
 
    Ramanujan_Numbers(n);
}
}
 
// This code is contributed by 29AjayKumar


Python3




# Python3 program to find Ramanujan numbers
from math import log, ceil
MAX = 1000000
 
# FUnction to return a vector of primes
def addPrimes():
 
    n = MAX
 
    # Create a boolean array "prime[0..n]"
    # and initialize all entries it as true.
    # A value in prime[i] will finally be
    # false if i is Not a prime, else true.
    prime = [True for i in range(n + 1)]
 
    for p in range(2, n + 1):
        if p * p > n:
            break
             
        # If prime[p] is not changed,
        # then it is a prime
        if (prime[p] == True):
 
            # Update all multiples of p
            # greater than or equal to the
            # square of it. numbers which are
            # multiple of p and are less than p^2
            # are already been marked.
            for i in range(2 * p, n + 1, p):
                prime[i] = False
 
    ans = []
     
    # Print all prime numbers
    for p in range(2, n + 1):
        if (prime[p]):
            ans.append(p)
 
    return ans
     
# Function to find number of primes
# less than or equal to x
def pi(x, v):
 
    l, r = 0, len(v) - 1
 
    # Binary search to find out number of
    # primes less than or equal to x
    m, i = 0, -1
    while (l <= r):
        m = (l + r) // 2
        if (v[m] <= x):
            i = m
            l = m + 1
        else:
            r = m - 1
 
    return i + 1
 
# Function to find the nth ramanujan prime
def Ramanujan(n, v):
 
    # For n>=1, a(n)<4*n*log(4n)
    upperbound = ceil(4 * n * (log(4 * n) / log(2)))
 
    # We start from upperbound and find where
    # pi(i)-pi(i/2)<n the previous number being
    # the nth ramanujan prime
    for i in range(upperbound, -1, -1):
        if (pi(i, v) - pi(i / 2, v) < n):
            return 1 + i
 
# Function to find first n Ramanujan numbers
def Ramanujan_Numbers(n):
    c = 1
 
    # Get the prime numbers
    v = addPrimes()
 
    for i in range(1, n + 1):
        print(Ramanujan(i, v), end = "")
        if(i != n):
            print(end = ", ")
 
# Driver code
n = 10
 
Ramanujan_Numbers(n)
 
# This code is contributed
# by Mohit Kumar


C#




// C# program to find Ramanujan numbers
using System;
using System.Collections.Generic;
 
class GFG
{
static int MAX = 1000000;
 
// FUnction to return a vector of primes
static List<int> addPrimes()
{
    int n = MAX;
 
    // Create a boolean array "prime[0..n]" and
    // initialize all entries it as true.
    // A value in prime[i] will finally be false
    // if i is Not a prime, else true.
    Boolean []prime = new Boolean[n + 1];
    for(int i = 0; i < n + 1; i++)
        prime[i] = true;
 
    for (int p = 2; p * p <= n; p++)
    {
        // If prime[p] is not changed,
        // then it is a prime
        if (prime[p] == true)
        {
            // Update all multiples of p greater than
            // or equal to the square of it
            // numbers which are multiple of p and are
            // less than p^2 are already been marked.
            for (int i = p * p; i <= n; i += p)
                prime[i] = false;
        }
    }
 
    List<int> ans = new List<int>();
     
    // Print all prime numbers
    for (int p = 2; p <= n; p++)
        if (prime[p])
            ans.Add(p);
 
    return ans;
}
 
// Function to find number of primes
// less than or equal to x
static int pi(int x, List<int> v)
{
    int l = 0, r = v.Count - 1, m, i = -1;
 
    // Binary search to find out number of
    // primes less than or equal to x
    while (l <= r)
    {
        m = (l + r) / 2;
        if (v[m] <= x)
        {
            i = m;
            l = m + 1;
        }
        else
        {
            r = m - 1;
        }
    }
    return i + 1;
}
 
// Function to find the nth ramanujan prime
static int Ramanujan(int n, List<int> v)
{
    // For n>=1, a(n)<4*n*log(4n)
    int upperbound = (int) (4 * n * (Math.Log(4 * n) /
                                     Math.Log(2)));
 
    // We start from upperbound and find where
    // pi(i)-pi(i/2)<n the previous number being
    // the nth ramanujan prime
    for (int i = upperbound;; i--)
    {
        if (pi(i, v) - pi(i / 2, v) < n)
            return 1 + i;
    }
}
 
// Function to find first n Ramanujan numbers
static void Ramanujan_Numbers(int n)
{
    int c = 1;
 
    // Get the prime numbers
    List<int> v = addPrimes();
 
    for (int i = 1; i <= n; i++)
    {
        Console.Write(Ramanujan(i, v));
        if(i != n)
            Console.Write(", ");
    }
}
 
// Driver code
public static void Main(String[] args)
{
    int n = 10;
 
    Ramanujan_Numbers(n);
}
}
 
// This code is contributed by 29AjayKumar


Javascript




<script>
// Javascript program to find Ramanujan numbers
 
const MAX = 1000000;
 
// FUnction to return a vector of primes
function addPrimes()
{
    let n = MAX;
 
    // Create a boolean array "prime[0..n]" and initialize
    // all entries it as true. A value in prime[i] will
    // finally be false if i is Not a prime, else true.
    let prime = new Array(n + 1).fill(true);
     
    for (let p = 2; p * p <= n; p++)
    {
        // If prime[p] is not changed, then it is a prime
        if (prime[p] == true)
        {
            // Update all multiples of p greater than or
            // equal to the square of it
            // numbers which are multiple of p and are
            // less than p^2 are already been marked.
            for (let i = p * p; i <= n; i += p)
                prime[i] = false;
        }
    }
 
    let ans = [];
    // Print all prime numbers
    for (let p = 2; p <= n; p++)
        if (prime[p])
            ans.push(p);
 
    return ans;
}
// Function to find number of primes
// less than or equal to x
function pi(x, v)
{
    let l = 0, r = v.length - 1, m, inn = -1;
 
    // Binary search to find out number of
    // primes less than or equal to x
    while (l <= r) {
        m = parseInt((l + r) / 2);
        if (v[m] <= x) {
            inn = m;
            l = m + 1;
        }
        else {
            r = m - 1;
        }
    }
    return inn + 1;
}
 
// Function to find the nth ramanujan prime
function Ramanujan(n, v)
{
    // For n>=1, a(n)<4*n*log(4n)
    let upperbound = 4 * n * parseInt((Math.log(4 * n) / Math.log(2)));
 
    // We start from upperbound and find where
    // pi(i)-pi(i/2)<n the previous number being
    // the nth ramanujan prime
    for (let i = upperbound;; i--) {
        if (pi(i, v) - pi(parseInt(i / 2), v) < n)
            return 1 + i;
    }
}
 
// Function to find first n Ramanujan numbers
function Ramanujan_Numbers(n)
{
    let c = 1;
 
    // Get the prime numbers
    let v = addPrimes();
 
    for (let i = 1; i <= n; i++) {
        document.write(Ramanujan(i, v));
        if(i!=n)
            document.write(", ");
    }
}
 
// Driver code
    let n = 10;
 
    Ramanujan_Numbers(n);
 
</script>


Output: 

2, 11, 17, 29, 41, 47, 59, 67, 71, 97

Time Complexity : O(nlogn)

Auxiliary Space: O(MAX)
 



Similar Reads

Count numbers in a given range having prime and non-prime digits at prime and non-prime positions respectively
Given two integers L and R, the task is to find the count of numbers in the range [L, R] having prime digits at prime positions and non-prime digits at non-prime positions. Examples: Input: L = 5, R = 22 Output: 7Explanation: The numbers 6, 8, 9, 12, 13, 15, and 17 have prime digits at prime positions and non-prime digits at non-prime positions. In
15 min read
Ramanujan–Nagell Conjecture
The Ramanujan-Nagell equation is an equation between a number (say, x) which is squared and another number (say, z) such that z = [Tex]2^n - 7[/Tex]. Here, n can be any positive natural number which satisfies the equation. It is an example of an exponential Diophantine equation, which is an equation that can have only integral solutions with one of
1 min read
Hardy-Ramanujan Theorem
Hardy Ramanujam theorem states that the number of prime factors of n will approximately be log(log(n)) for most natural numbers nExamples : 5192 has 2 distinct prime factors and log(log(5192)) = 2.1615 51242183 has 3 distinct prime facts and log(log(51242183)) = 2.8765 As the statement quotes, it is only an approximation. There are counter examples
6 min read
Find all Ramanujan Numbers that can be formed by numbers upto L
Given a positive integer L, the task is to find all the Ramanujan Numbers that can be generated by any set of quadruples (a, b, c, d), where 0 &lt; a, b, c, d ? L. Ramanujan Numbers are the numbers that can be expressed as sum of two cubes in two different ways. Therefore, Ramanujan Number (N) = a3 + b3 = c3 + d3. Examples: Input: L = 20Output: 172
15 min read
Prime numbers after prime P with sum S
Given three numbers sum S, prime P, and N, find all N prime numbers after prime P such that their sum is equal to S.Examples : Input : N = 2, P = 7, S = 28 Output : 11 17 Explanation : 11 and 17 are primes after prime 7 and (11 + 17 = 28) Input : N = 3, P = 2, S = 23 Output : 3 7 13 5 7 11 Explanation : 3, 5, 7, 11 and 13 are primes after prime 2.
13 min read
Sum of each element raised to (prime-1) % prime
Given an array arr[] and a positive integer P where P is prime and none of the elements of array are divisible by P. Find sum of all the elements of the array raised to the power P - 1 i.e. arr[0]P - 1 + arr[1]P - 1 + ... + arr[n - 1]P - 1 and print the result modulo P.Examples: Input: arr[] = {2, 5}, P = 3 Output: 2 22 + 52 = 29 and 29 % 3 = 2Inpu
3 min read
Print the nearest prime number formed by adding prime numbers to N
Given a number N. The task is to print the nearest prime if the number is not prime by making it prime by adding prime numbers sequentially from 2. Examples: Input: N = 8 Output: 13 8 is not prime, so add the first prime to it to get 10 10 is not prime, hence add the second prime, i.e., 3 to get 13 which is prime. Input: N = 45 Output: 47 Naive App
11 min read
Maximize difference between sum of prime and non-prime array elements by left shifting of digits minimum number of times
Given an array arr[] of size N, the task is to find the maximum difference between the sum of the prime numbers and the sum of the non-prime numbers present in the array, by left shifting the digits of array elements by 1 minimum number of times. Examples: Input: arr[] = {541, 763, 321, 716, 143}Output: Difference = 631, Count of operations = 6Expl
14 min read
Absolute Difference between the Sum of Non-Prime numbers and Prime numbers of an Array
Given an array of positive numbers, the task is to calculate the absolute difference between sum of non-prime numbers and prime numbers. Note: 1 is neither prime nor non-prime. Examples: Input : 1 3 5 10 15 7 Output : 10 Explanation: Sum of non-primes = 25 Sum of primes = 15 Input : 3 4 6 7 Output : 0 Naive Approach: A simple solution is to travers
16 min read
Absolute difference between the Product of Non-Prime numbers and Prime numbers of an Array
Given an array of positive numbers, the task is to calculate the absolute difference between product of non-prime numbers and prime numbers.Note: 1 is neither prime nor non-prime.Examples: Input : arr[] = {1, 3, 5, 10, 15, 7} Output : 45 Explanation : Product of non-primes = 150 Product of primes = 105 Input : arr[] = {3, 4, 6, 7} Output : 3 Naive
15 min read
Article Tags :
Practice Tags :