Belzabar Software Design Hiring Coding Question | Computer Scientist (Developer position)
Question: Belzabar is 19 years old. On this occasion, we formulated the Belzabar Number. A positive integer is a Belzabar number if it can be represented either as (n * (n + 19)) OR (n * (n — 19)), where n is a prime number.
Write a function named ‘isBelzabarNumber( )’ which accepts a number as input and determines if it is a Belzabar Number (or not). Input to the function will be a number and the output will be Boolean.
For bonus points:
- Write a function that calculates and prints the count of Belzabar numbers less than or equal to 1 million.
- Write a function that calculates and prints the count of Belzabar numbers from bonus question #1 above that are prime.
There are additional bonus points for elegance, adequate code comments describing the algorithm(s) used, focus on coding conventions, optimal speed and time complexity and readability.
Explanation: Here we have to find if the given input is belzabar number or not and belzabar number is represented as (n * (n +19)) or (n * (n -19)) where n is a prime number. Let the given number is b then it must be equivalent to (n * (n +19)) or (n * (n -19)).
Belzabar number b = (n * (n +19)) or (n * (n -19))
e.g. b = 66 is a belzabar number.
n = 2 (starting from 2 because 0 and 1 are not prime number)
b = (n * (n + 19)) => (2 * ( 2 +19) => 42 != 66 (n = 2)
b = (n * (n + 19)) => (3* (3 + 19) => 66 == 66 (n = 3)
import java.util.*;
public class GFG {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int b = 1550;
GFG gf = new GFG();
// Printing is number is belzabar
System.out.println("Belzabar Hiring | Coding question");
if(gf.isBelzabarNumber(b)){
System.out.println(b + " is Belzabar Number");
} else{
System.out.println(b + " is not a Belzabar Number");
}
sc.close();
}
boolean isBelzabarNumber(int b)
{
for (int n = 2; n < 1000; n++) {
// Taking the number n from 2 to 1000 as 1 is
// already not a prime
if (isPrime(n)) {
// If number is prime then we check if it is
// representable in the form of (n*(n-19))
// or (n*(n-19))
if ((b == (n * (n + 19)))
|| (b == (n * (n - 19)))) {
// If the number b is equal to the above
// equation then it returns true
return true;
}
}
}
return false;
}
// Checking if the number n is prime or not
boolean isPrime(int n)
{
if (n == 2)
return true; // 2 is already prime number
// If number n is prime then we return true
for (int i = 3; i < n / 2; i++) {
if (n % i == 0)
return false;
}
return true;
}
}
Note: Dear readers, This code is just for your reference. Kindly try to design your own logic and please don’t copy-paste the code.
Thanks!