×

Balanced Prime Number in Java

This section will cover the definition of a balanced prime number as well as how to find one using a Java program.

Balance Prime Number

A prime number that is equivalent to the average of the immediately preceding and following prime numbers is said to be balanced.

Let's use examples to better grasp it.

Example 1:

Input: 13

The result is that 13 is an unbalanced prime number.

Reason: The prime number that comes after the number 13 is 17, and the prime number that comes before it is 11. Their average is (11 + 17) / 2 = 28 / 2 = 14, which is not the same as the number 13. 13 is not an balanced prime number as a result.

Example 2:

Input: 53

53 is a prime number that is balanced.

Explanation: The prime number that is right after the value 53 is 59, and the prime number that is right before the number 53 is 47. The average of these two prime numbers is (47 + 59) / 2 = 106 / 2 = 53, that is the same as the input number. 53 is indeed a balanced prime number as a result.

Naive Approach

In this method, we'll employ two distinct loops. One is used to calculate the prime number that comes right after the input prime number, and the other is used to calculate the prime number that comes right after it. Then, in order to determine if the average is equal to an input prime number or not, we calculate the average of immediately preceding and following prime numbers. Take note of the program below.

BalancedPrimeExpl1.java

public class BalancedPrimeExpl1   
{  
public boolean isPrime(int n)  
{  
if(n == 0 || n == 1)  
{  
return false;  
}  
// Since the Math.sqrt method
// returns double, we must 
// modify it to int.  
int m = (int)Math.sqrt(n);  
for(int j = 2; j <= m; j++)  
{  
if(n % j == 0)  
{  
// reaching here indicates 
// that we have a factor that 
// is not 1, and therefore num 
// is not prime, so we return false. 
return false;  
}  
}  
return true;  
}  
public boolean isBalancedPrime(int n)  
{  
float g = n;  
// to store the previous prime we 
// keep the current n as the reference  
float pN = -1f;  
// for storing the next prime by  
// keeping the current num as the reference  
float nextNum = -1f;  
// finding the immediate previous prime  
for(float j = n - 1f; j >= 2f; j--)  
{  
if(isPrime((int)j))  
{  
// immediate previous prime has been found  
// so we can break the loop  
pN = j;  
break;  
}  
}  
// finding the immediate next prime  
for(float k = n + 1f; true; k++)  
{  
if(isPrime((int)k))  
{  
// immediate next prime has been found  
// so we can break the loop  
nextNum = k;  
break;  
}  
}  
if(pN == -1f)  
{       
// the previous prime number   
// is not found so we have
// reached here 
return false;  
}  
// calculating the average of the p and the nextNum  
float a = (pN + nextNum) / 2f;  
if(g == a)  
{  
return true;  
}  
return false;  
}  
public static void main(String args[])  
{  
// creating an instance for the class BalancedPrimeExpl1  
BalancedPrimeExpl1 o = new BalancedPrimeExpl1();  
  
System.out.println(" Total number of balanced primes are: ");  
  
for(int j = 1; j <= 200; j++)  
{  
if(o.isPrime(j) && o.isBalancedPrime(j))  
{  
System.out.print(j + " ");  
}  
}  
}  
}  

Output:

Balanced Prime Number in Java

Time complexity:

A prime number num is taken into consideration along with the assumptions that the immediately preceding prime number is m distances away from num and the immediately following prime number is n distances away from num. Assume that k is the biggest number you've found while looking for the immediately preceding prime number, and l is the biggest number you've found while looking for the immediately following prime number. As a result, the program has an O(m + n) time complexity for each num.

It is annoying because, in order to calculate the immediately following and immediately preceding prime numbers, we must examine each number's previous value as well as its next value. We can utilize the filter invented by Eratosthenes to prevent that. Keep in mind the following.

Using the Sieve of Eratosthenes Algorithm

BalancedPrimeExpl2.java

public class BalancedPrimeExpl2  
{  
public boolean primeArr[];  
public void sieveofNumbers(int m)  
{  
// making a boolean primeArr[0... n] array and setting each
//  entry's initial value to true. 
// If k is not a prime number, the value of 
// primeArr[j] will ultimately be false, otherwise true.
primeArr = new boolean[m + 1];  
for(int j = 0; j <= m; j++)  
{  
primeArr[j] = true;  
}  
for(int k = 2; k * k <= m; k++)  
{  
// If primeArr[k] is not changing, then it is a prime number  
if(primeArr[k] == true)  
{  
// updating all the multiples of k 
for(int j = k * k; j <= m; j += k)  
{  
primeArr[j] = false;  
}  
}  
}  
}  
public boolean isBalancedPrime(int n)  
{  
float g = n;  
// to store the previous prime we  
// keep the current num as the reference  
float pN = -1f;  
// to store the next prime we  
// keep the current num as the reference  
float nextNum = -1f;  
// finding the immediate previous prime  
for(float j = n - 1f; j >= 2f; j--)  
{  
if(primeArr[(int)j])  
{  
// after the previous prime is found  
// we can break the loop  
pN = j;  
break;  
}  
}  
// finding the immediate next prime  
for(float k = n + 1f; true; k++)  
{  
if(primeArr[(int)k])  
{  
// after the next prime is found  
// we can break the loop  
nextNum = k;  
break;  
}  
}  
if(pN == -1f)  
{      
// the previous prime number   
// is not found so we
//  are reaching here 
return false;  
}  
// calculating the average of the pN and the nextNum  
float a = (pN + nextNum) / 2f;  
if(g == a)  
{  
return true;  
}  
return false;  
}  
public static void main(String args[])  
{  
// creating an instance for the class BalancedPrimeExpl2  
BalancedPrimeExpl2 o = new BalancedPrimeExpl2();  
o.sieveofNumbers(300);  
System.out.println(" Total number of balanced primes are : ");  
for(int j = 1; j <= 200; j++)  
{  
if(o.primeArr[j] && o.isBalancedPrime(j))  
{  
System.out.print(j + " ");  
}  
}  
}  
}

Output:

Balanced Prime Number in Java

Time complexity:

The temporal complexity of the aforementioned program is O(m + n + k.log(k)) for any prime number num, where m is the distance between the prime number and num that comes immediately before it and n is the distance between num and the prime number that comes immediately after it. For which the sieve is calculated, k is the range.

Remember

If the sum of the immediately following prime number and the immediately smaller prime number is less than a prime number num, that number is said to be a weak prime number.

A prime number is said to be a strong prime number if the average of the two prime numbers right after it and the one right before it is greater than the number num.


Related Topics

Series Program in Java

Series Program in Java The series program in Java is written to print the mathematical series such as the Fibonacci series, Pell series, etc. A few of the renowned series are...

12 minutes read.

Java Regular Expressions

Java Regular Expressions The Java Regex or Regular Expression is an API that defines a pattern for searching or manipulating strings. A regular expression is a pattern that can be as simple as...

8 minutes read.

Streams in Java

The conventional Java SE 8 version came with many new peculiarities, out of which the most striking of which are assuredly lambda expressions and the method references. Streams and Streams...

14 minutes read.

How to sort a String in Java

Sorting is the process of putting the elements in a certain order, either ascending or descending. Mostly the alphabetical order or natural order is used for a string. In other...

5 minutes read.

Display List of TimeZone with GMT and UTC in Java

It is vital to establish the right TimeZone in Java code when working with dates for Daylight Saving Time. In this part, we will present the time zones with GMT. TimeZone Those...

5 minutes read.

Empty Statement in Java

The three sorts of statements in Java are control, expression, and declaration statements. Additionally, another statement is referred to as an empty statement. In this section, we will discuss about...

4 minutes read.

Java Math nextAfter() Method

The nextAfter() method of Math class returns the floating-point value adjacent to the first argument in direction of the second argument. Syntax: public static double nextAfter (double start, double direction)public static float...

2 minutes read.

Operators in Java

There is a good operator environment provided by Java. These operators are divided into four different groups i.e. arithmetic, bitwise, relational, and logical. There are other operators also available to...

7 minutes read.

Statements in java

What is Statement in java: A statement in java is an instruction that explains what will happen based on the condition. Types of java statements: There are different statements in java Expression statementDeclaration statementControl...

2 minutes read.

String Declaration in Java

A string is a group of characters. In Java, the string can be treated as both class and datatype. In Java programming, the String class have many advantages. Everything in...

3 minutes read.

How to check Date Null in Java?

In this section, we will be acknowledged about Date Null in Java. The date null in Java is an entity that is used when there is no specified value for...

3 minutes read.

Java Math atan2() Method

The atan2() method of Math class returns an angle theta from the conversion of rectangular coordinates to polar coordinates. Syntax: public static double atan2(double y, double x) Parameters: The parameter ‘y’ represents the ordinate...

3 minutes read.

Java exception list

Java uses exceptions, like the majority of contemporary programming languages, to deal with both errors and "extraordinary events." When an exception arises inside the program, it messes up the regular...

6 minutes read.

How to convert float to String in Java

How to convert float to String in java There are following methods to convert float to String: Convert using Float.toString(float) Convert using String.valueOf(float) Convert using Float.toString(float) The Float class has a static method that returns...

2 minutes read.

How to install Java in Windows 10

To make programs that can run on our systems, we need to install the programming language related software in our systems. Different programming language requires a different type of software aka...

6 minutes read.

What’s new in Java 12

On March 19th, 2019, the Java 12th edition was released. After releasing this edition, they have decided to release every new edition every six months. This version is the advanced...

5 minutes read.

Balanced Prime Number in Java

This section will cover the definition of a balanced prime number as well as how to find one using a Java program. Balance Prime Number A prime number that is equivalent to...

5 minutes read.

Sealed Class in Java

What is a Sealed Class in Java? In programming, the two main issues that must be taken into account when creating an application are security and control flow. The use of...

5 minutes read.

How to get Day Name from Date in Java

We'll write a Java application to extract the day's name from the Date in this section. When dealing with Date and time in Java, the following classes are used. Class for Calendars:...

6 minutes read.

Heap Implementation in Java

The root node or parent node of a Java heap is compared to its left and right offspring, and the children are then ordered in line with the comparison.Assuming that...

9 minutes read.