Following is the code:
let i, j;
function isPrime(x) {
for (j = 2; j < int(Math.sqrt(x)) + 1; j++) {
if (x % j == 0)
return False;
return True;
}
}
function findPrimeNum() {
let number = document.getElementById("inputNumber");
for (i = number - 1; i > 1; i--) {
if (isPrime(i) == True)
document.getElementById('result').innerHTML = 'Largest prime less than or equal to ' + number + ': ' + i;
return i;
}
}
<!-- Input field and button -->
<input type="number" id="inputNumber" placeholder="Enter a number">
<button onclick="findPrimeNum()">Find Largest Prime</button>
<!-- Result display -->
<p id="result"></p>
I have tried doing return True; below the for block. I have also tried taking innerHTML
outside the function. Shows no error on console. Please check
It looks like there are a few issues with your JavaScript code which might be causing the function not to behave as expected. Here's a revised version of your code along with explanations for the changes:
function isPrime(x) {
if (x <= 1) return false; // Add this line to handle cases where x is 1 or less.
for (let j = 2; j <= Math.sqrt(x); j++) { // Changed 'int' to 'let' for proper syntax and initialization.
if (x % j == 0)
return false; // Return should be lowercase.
}
return true; // This return statement should be outside the for loop.
}
function findPrimeNum() {
let number = parseInt(document.getElementById("inputNumber").value); // Added .value to actually get the input value.
for (let i = number; i > 1; i--) { // Changed 'let' from 'i = number - 1' to 'i = number' to include the possibility that 'number' itself is prime.
if (isPrime(i)) { // Removed "== True" as it is unnecessary.
document.getElementById('result').innerHTML = 'Largest prime less than or equal to ' + number + ': ' + i;
return; // Removed 'return i;' to prevent the function from terminating before updating the innerHTML.
}
}
document.getElementById('result').innerHTML = 'No primes found.'; // Handles the case where no primes are found.
}