Reputation: 101
Trying to write a javascript function that accepts 2 positive integers and returns the highest prime number between them, otherwise, returns an appropriate error message.E.g. if input numbers are 50 and 75, the output should be 73 and if the input numbers are -50,-75, output should be an error message.
But I am not sure why my code is returning the highest odd number.
Here is my code:
function highestPrimeInRange(int1, int2) {
if (int1 <= 0 || int2 <= 0) {
alert("Both numbers should be positive and non 0");
}
let highestPrime;
for (let i = int1; i <= int2; i++) {
let primeFlag = true;
for (let j = 2; j <= i / 2; j++) {
if (i % j == 0) {
primeFlag = false;
break;
}
if (primeFlag) {
highestPrime = i;
}
}
}
alert(highestPrime);
}
highestPrimeInRange(50, 75);
Can someone please help me out where I am going wrong?
Upvotes: 0
Views: 153
Reputation: 782785
The code that updates highestPrime
should be outside the j
loop. You also need to return from the function when the inputs are out of range, rather than continue with the prime-finding code.
function highestPrimeInRange(int1, int2) {
if (int1 <= 0 || int2 <= 0) {
alert("Both numbers should be positive and non 0");
return;
}
if (int1 >= int2) {
alert("First number should be less than second");
return;
}
let highestPrime;
for (let i = int1; i <= int2; i++) {
let primeFlag = true;
for (let j = 2; j <= i / 2; j++) {
if (i % j == 0) {
primeFlag = false;
break;
}
}
if (primeFlag) {
highestPrime = i;
}
}
alert(highestPrime);
}
highestPrimeInRange(50, 75);
highestPrimeInRange(-50, -75);
highestPrimeInRange(10, 100);
But it would be better to loop down from the highest number, and stop when you get the first prime.
function highestPrimeInRange(int1, int2) {
if (int1 <= 0 || int2 <= 0) {
alert("Both numbers should be positive and non 0");
return;
}
if (int1 >= int2) {
alert("First number should be less than second");
return;
}
for (let i = int2; i >= int1; i--) {
let primeFlag = true;
for (let j = 2; j <= i / 2; j++) {
if (i % j == 0) {
primeFlag = false;
break;
}
}
if (primeFlag) {
alert(i);
break;
}
}
}
highestPrimeInRange(50, 75);
highestPrimeInRange(-50, -75);
highestPrimeInRange(10, 100);
There are also more efficient ways to test if it's prime: you can just test the odd numbers, you only need to check for division by odd factors, you only need to test up to Math.sqrt(i)
rather than i/2
.
Upvotes: 4