This is an interesting topic!
To check if a number is prime number, we have to divide it with all the numerical values between 2 and the number it self and check for reminder.
Typical implementation,
boolean isPrimeNumber(long number) {
for(int i=2; i<number; i++) {
if(number % i == 0)
return false;
}
return true;
}
Possible optimizations....
- We don't have to iterate more than half of the number while even, you know if the value is more than half then multiplying it by two will lead to more than what we want.
- We don't have to iterate more than 1/3rd of the number while odd, assuming to be divisible by 3.
Optimized implementation,
static boolean isPrimeNumber(float number) {
float iterateTill = 0;
if(number%1 != 0) {
return false;
}
if (number%2 == 0) {
iterateTill = number/2;
}
else {
iterateTill = number/3;
}
for(int i=2; i<=iterateTill; i++) {
if(number % i == 0)
return false;
}
return true;
}
I will think over this and if I find any better solution, I will post it.
Hope this helps!
Update 1:
Sorry for not understanding the question thoroughly! This method prints the result you seek. Assuming there could be more than 2 prime numbers multiplied in the provided number. I will refine the code further....
static boolean getPrimeNumbersWithin(long number) {
long firstNumber = 2;
long secondNumber = 2;
float remainingNumber = number;
while(remainingNumber > 0 && firstNumber < number) {
remainingNumber = (float)number/(float)firstNumber;
if(isWholeNumber(remainingNumber)) {
if(isPrimeNumber(remainingNumber)) {
secondNumber = (long)remainingNumber;
remainingNumber = 0;
break;
}
else {
// try if this could be acheived with more numbers
if (getPrimeNumbersWithin((long)remainingNumber)) {
secondNumber = 0;
remainingNumber = 0;
break;
}
}
}
do {
firstNumber++;
}
while(!isPrimeNumber(firstNumber));
}
if(remainingNumber == 0) {
System.out.println(firstNumber);
if(secondNumber != 0){
System.out.println(secondNumber);
}
return true;
}
else {
System.out.println("No match");
return false;
}
}
static boolean isWholeNumber(float number) {
if(number%1 != 0) {
return false;
}
return true;
}
Test run result,
getPrimeNumbersWithin(6090); // Results 7 29 5 3 2
online link for your immediate reference.