×

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

Stack Program in Java

Stack Program in Java The Stack class is part of the collection framework that inherits the Vector class. Thus, the Stack class can also be called a subclass of the Vector...

5 minutes read.

How to convert list to String in Java

Sometimes, we need to transform a listing of characters into a string. A string is a chain of characters, so we will make a string from an individual array without...

4 minutes read.

Java Network Programming (Socket Programming in Java)

JAVA NETWORK Network programming is used to execute programs across multiple machines that are connected by a network. The java.net package contains a collection of classes and interfaces that provide this...

3 minutes read.

Swing Program in Java

Java Swing is part of Java Foundation Classes (JFC). The swing toolkit is used to generate Graphical User Interface (GUI) for programs written in Java. The Java swing API is...

4 minutes read.

Zig Zag star and Number Pattern in Java

We covered many Java pattern applications in the preceding part. We will write Java applications for zigzag star and number patterns in this part. Printing Zig Zag Number Pattern Steps Print one...

3 minutes read.

Compile time vs Runtime in java

Introduction: This article will discuss compile time vs. runtime in java. Compile time and runtime are two programming terms utilized in software improvement. Compile time is when the source code is...

3 minutes read.

Difference Between replace() and replaceall() in Java

In this article, you will be acknowledged about the replace() and replaceall() methods in java. Also, most importantly you will be acknowledged the differences between them along with the example...

4 minutes read.

JDBC Program in Java

JDBC Program in Java JDBC is an API that defines how a client may access a database. It is a part of Java Standard Edition (Java SE). JDBC stands for Java...

4 minutes read.

Java LinkedList

LinkedList Java The Java LinkedList is used to store the elements by using a doubly linked list. It contains the duplicate items, also maintains the order of the insertion, the class...

5 minutes read.

Equidigital in Java

In this section, we will understand what is an equidigital number and how to write Java programs to locate them. It is commonly asked in academic settings and Java coding...

4 minutes read.

How to Convert Object to String in Java

How to Convert Object to String in Java You can convert any Object to String in Java whether it is a user-defined class, StringBuilder or StringBuffer, etc. There are two methods...

2 minutes read.

Check whether Java is installed or not

As we know that there are various operating systems, to check whether Java is installed or not in Windows and Mac we use the following ways.           Windows Operating System: There are several...

2 minutes read.

Split String into String Array in Java

The String split() technique returns a variety of divided strings after the strategy parts the given String around matches of a given normal articulation containing the delimiters. The ordinary articulation...

4 minutes read.

Java Math toDegrees() Method

The toDegrees() method of Java Math class converts a radian angle to an approximately equivalent angle measured in degrees. Syntax: public static double toDegrees(double angrad) Parameters: The parameter ‘angrad ‘represents an angle measured in...

2 minutes read.

Java Obfuscator

Obfuscation is the process of making something unclear or difficult to interpret. Obfuscators are being used in programming to protect the source code from hackers. In this article, we will...

8 minutes read.

Java concurrency interview questions

During technical interviews, one of the most challenging and sophisticated subjects is concurrency in Java. This page offers responses to some of the related interview questions you might come across. 1....

11 minutes read.

Java Generics Questions

Introduction We'll walk through a few real-world examples of interview questions and responses for Java generics in this article. Java 5 saw the debut of the fundamental idea of generics. Due to...

9 minutes read.

Java Primitive Data Types

Primitive data types are the simplest data types in a programming language. They’re predefined in the language. The names of the primitive types are quite descriptive of the values that...

2 minutes read.

Java HashSet

HashSet implements the set interface. It uses the hash table to make the collection to store different data types. The hash set is the unordered collection of different data types....

6 minutes read.

Difference Between Java and PHP

The two most used programming languages are PHP and Java. Both of them have a lot of similarities and distinctions. Let's first grasp each of them individually before examining their...

3 minutes read.