In number theory, a Balanced Prime is a prime number with equal-sized prime gaps above and below it, so that it is equal to the arithmetic mean of the nearest primes above and below. Or to put it algebraically, given a prime number pn, where n is its index in the ordered set of prime numbers,
\Huge p_n= \frac{p_{n-1}+p_{n+1}}{2}
First few balanced prime are 5, 53, 157, 173......
Given a positive integer N. The task is to print Nth balanced prime number.
Examples:
Input : n = 2
Output : 53
Input : n = 3
Output : 157
The idea is to generate prime numbers using Sieve of Eratosthenes and store it in an array. Now iterate over the array to check whether it is balanced prime or not and keep counting the balanced prime. Once you reach the nth prime, return it.
Below is the implementation of this approach:
C++
// CPP Program to find Nth Balanced Prime
#include<bits/stdc++.h>
#define MAX 501
using namespace std;
// Return the Nth balanced prime.
int balancedprime(int n)
{
// Sieve of Eratosthenes
bool prime[MAX+1];
memset(prime, true, sizeof(prime));
for (int p = 2; p*p <= MAX; p++)
{
// If prime[p] is not changed, then it is a prime
if (prime[p] == true)
{
// Update all multiples of p
for (int i = p*2; i <= MAX; i += p)
prime[i] = false;
}
}
// storing all primes
vector<int> v;
for (int p = 3; p <= MAX; p += 2)
if (prime[p])
v.push_back(p);
int count = 0;
// Finding the Nth balanced Prime
for (int i = 1; i < v.size(); i++)
{
if (v[i] == (v[i+1] + v[i - 1])/2)
count++;
if (count == n)
return v[i];
}
}
// Driven Program
int main()
{
int n = 4;
cout << balancedprime(n) << endl;
return 0;
}
Java
// Java Program to find Nth Balanced Prime
import java.util.*;
public class GFG
{
static int MAX = 501;
// Return the Nth balanced prime.
public static int balancedprime(int n)
{
// Sieve of Eratosthenes
boolean[] prime = new boolean[MAX+1];
for(int k = 0 ; k < MAX+1; k++)
prime[k] = true;
for (int p = 2; p*p <= MAX; p++)
{
// If prime[p] is not changed,
// then it is a prime
if (prime[p] == true)
{
// Update all multiples of p
for (int i = p*2; i <= MAX;
i += p)
prime[i] = false;
}
}
// storing all primes
Vector<Integer> v =
new Vector<Integer>();
for (int p = 3; p <= MAX; p += 2)
if (prime[p])
v.add(p);
int count = 0;
// Finding the Nth balanced Prime
for (int i = 1; i < v.size(); i++)
{
if ((int)v.get(i) == ((int)v.get(i+1)
+ (int)v.get(i-1))/2)
count++;
if (count == n)
return (int) v.get(i);
}
return 1;
}
// Driven Program
public static void main(String[] args)
{
int n = 4;
System.out.print(balancedprime(n));
}
}
// This code is contributed by Prasad Kshirsagar
Python3
# Python3 code to find Nth Balanced Prime
MAX = 501
# Return the Nth balanced prime.
def balancedprime( n ):
# Sieve of Eratosthenes
prime = [True]*(MAX+1)
p=2
while p * p <= MAX:
# If prime[p] is not changed,
# then it is a prime
if prime[p] == True:
# Update all multiples of p
i = p * 2
while i <= MAX:
prime[i] = False
i = i + p
p = p +1
# storing all primes
v = list()
p = 3
while p <= MAX:
if prime[p]:
v.append(p)
p = p + 2
count = 0
# Finding the Nth balanced Prime
i=1
for i in range(len(v)):
if v[i] == (v[i+1] + v[i - 1])/2:
count += 1
if count == n:
return v[i]
# Driven Program
n = 4
print(balancedprime(n))
# This code is contributed by "Sharad_Bhardwaj".
PHP
<?php
// PHP Program to find Nth Balanced Prime
$MAX=501;
// Return the Nth balanced prime.
function balancedprime($n)
{
global $MAX;
// Sieve of Eratosthenes
$prime=array_fill(0,$MAX+1,true);
for ($p = 2; $p*$p <= $MAX; $p++)
{
// If prime[p] is not changed, then it is a prime
if ($prime[$p] == true)
{
// Update all multiples of p
for ($i = $p*2; $i <= $MAX; $i += $p)
$prime[$i] = false;
}
}
// storing all primes
$v=array();
for ($p = 3; $p <= $MAX; $p += 2)
if ($prime[$p])
array_push($v,$p);
$count = 0;
// Finding the Nth balanced Prime
for ($i = 1; $i < count($v); $i++)
{
if ($v[$i] == ($v[$i+1] + $v[$i - 1])/2)
$count++;
if ($count == $n)
return $v[$i];
}
}
// Driven Program
$n = 4;
echo balancedprime($n);
// this code is contributed by mits.
?>
C#
// C# Program to find Nth Balanced Prime
using System;
using System.Collections.Generic;
public class GFG
{
static int MAX = 501;
// Return the Nth balanced prime.
public static int balancedprime(int n)
{
// Sieve of Eratosthenes
bool[] prime = new bool[MAX+1];
for(int k = 0 ; k < MAX+1; k++)
prime[k] = true;
for (int p = 2; p*p <= MAX; p++)
{
// If prime[p] is not changed,
// then it is a prime
if (prime[p] == true)
{
// Update all multiples of p
for (int i = p*2; i <= MAX;
i += p)
prime[i] = false;
}
}
// storing all primes
List<int> v = new List<int>();
for (int p = 3; p <= MAX; p += 2)
if (prime[p])
v.Add(p);
int c = 0;
// Finding the Nth balanced Prime
for (int i = 1; i < v.Count-1; i++)
{
if ((int)v[i]==(int)(v[i+1]+v[i-1])/2)
c++;
if (c == n)
return (int) v[i];
}
return 1;
}
// Driven Program
public static void Main()
{
int n = 4;
Console.WriteLine(balancedprime(n));
}
}
// This code is contributed by mits
JavaScript
<script>
// Javascript Program to find Nth Balanced Prime
var MAX = 501;
// Return the Nth balanced prime.
function balancedprime(n)
{
// Sieve of Eratosthenes
var prime = Array(MAX+1).fill(true);
for (var p = 2; p*p <= MAX; p++)
{
// If prime[p] is not changed, then it is a prime
if (prime[p] == true)
{
// Update all multiples of p
for (var i = p*2; i <= MAX; i += p)
prime[i] = false;
}
}
// storing all primes
var v = [];
for (var p = 3; p <= MAX; p += 2)
if (prime[p])
v.push(p);
var count = 0;
// Finding the Nth balanced Prime
for (var i = 1; i < v.length; i++)
{
if (v[i] == (v[i+1] + v[i - 1])/2)
count++;
if (count == n)
return v[i];
}
}
// Driven Program
var n = 4;
document.write( balancedprime(n) );
</script>
Output:
173
Time Complexity: O(m*log(log(m))) where m=MAX(501 in this code)
Auxiliary Space: O(m)
Similar Reads
Balanced Binary Tree A binary tree is balanced if the height of the tree is O(Log n) where n is the number of nodes. For Example, the AVL tree maintains O(Log n) height by making sure that the difference between the heights of the left and right subtrees is at most 1. Red-Black trees maintain O(Log n) height by making s
3 min read
Digitally balanced numbers Given two integers N and B, the task is to check N is a Digitally balanced number in base B. Digitally balanced numbers in the base B are those numbers that have the same number of (0, 1, 2 ....B-1) digits in base B. Examples: Input: N = 9, B = 2 Output: Yes Equivalent binary number of 9 is 1001, wh
5 min read
Maximum Balanced Subsequence Score Given a stock's prices for the past n days in the array stockPrice. Choose a subsequence (an ordered subset of an array's elements) of stock prices, called chosenDays, such that the chosen subsequence of stock prices is balanced. The score of the chosen subsequence is the sum of stock prices on the
7 min read
Maximum Balanced String Partitions Given a balanced string str of size N with an equal number of L and R, the task is to find a maximum number X, such that a given string can be partitioned into X balanced substring. A string called to be balanced if the number of 'L's in the string equals the number of 'R's. Examples: Input : str =
7 min read
Balance a Binary Search Tree Given a BST (Binary Search Tree) that may be unbalanced, the task is to convert it into a balanced BST that has the minimum possible height.Examples: Input: Output: Explanation: The above unbalanced BST is converted to balanced with the minimum possible height.Input: Output: Explanation: The above u
10 min read
Check if N is a Balanced Prime number or not Given a positive integer N, the task is to check if N is a Balanced Prime number or not. In number theory, a Balanced Prime is a prime number with equal-sized prime gaps above and below it, so that it is equal to the arithmetic mean of the nearest primes above and below. Or to put it algebraically,
8 min read
Longest Balanced Subsequence Given a string str, find the length of the longest balanced subsequence in it. A balanced string is defined as a string sequence that can form a valid balanced expression, consisting of matching opening and closing brackets. A null string is a balanced string.If X and Y are balanced strings, then (X
14 min read
Self Balancing BST in JavaScript A self-balancing binary search tree (BST) is a type of binary search tree that automatically keeps its height balanced in order to guarantee that operations such as searching, inserting, and deleting elements in the tree take less time on average. How do self-balancing BSTs maintain height balance?
11 min read
Introduction to Height Balanced Binary Tree A height-balanced binary tree is defined as a binary tree in which the height of the left and the right subtree of any node differ by not more than 1. AVL tree, red-black tree are examples of height-balanced trees. Height Balanced treeConditions for Height-Balanced Binary Tree: Following are the con
5 min read
Find the balanced node in a Linked List Given a linked list, the task is to find the balanced node in a linked list. A balanced node is a node where the sum of all the nodes on its left is equal to the sum of all the node on its right, if no such node is found then print -1. Examples: Input: 1 -> 2 -> 7 -> 10 -> 1 -> 6 -
8 min read