Java program to print Beprisque numbers between two numbers

A number is called a Beprisque if it is the only number between a prime and a square number ( i.e. that number should be a prime number plus one and a square number minus one OR a prime number minus one and a square number plus one). For example , 10 is a Beprisque number because it is the only number between 9 which is a square number and 11 which is a prime number . 24 is also a Beprisque number because 24 is the only number between 23 which is a prime and 25 which is a square number . Now the logic to find the Beprisque number will be as follows. Take a number n . The number n is Beprisque number , if n-1 is prime and n+1 is square number OR n+1 is prime number and n-1 is square number. To implement the above logic , I have written two functions . 1) isPrime() which is to check the number is prime or not . 2) isSquare() is to check the given number is square or not. The folllowing code prints all the Beprisque numbers between given two numbers (min and max) where min, max is accepted through keyboard. The logic to check the given number is square or not will be (Math.sqrt(num) == (int) Math.sqrt(num)) where num is the given number i.e. squareRoot of number (num) should be an integer
*/
    
import java.util.Scanner;
public class BeprisqueNumbers {
public static void main(String argv[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter min");
int min = sc.nextInt();
System.out.println("Enter max");
int max = sc.nextInt();
System.out.println("Beprisque Numbers between " + min + " and " + max);

//Logic to print Beprisque Numbers
for (int n = min; n < max; n++) {
if ( isPrime(n - 1) && isSquare((double)(n+ 1)) || isPrime(n+ 1) && isSquare((double)(n- 1)) ) System.out.println(n);
}
}
//to check prime number
public static boolean isPrime(int num) {
int i=0;
for ( i = 2; i < num ; i++) {
if ((num % i) == 0 ) return false;
}
return true;
}
//to check square
public static boolean isSquare(double num) {
return (Math.sqrt(num) == (int) Math.sqrt(num));
}
}


Output :

0 comments:

Post a Comment

 
Copyright 2011 Java Online