JavaScript - Prime Number
function is_Prime(num) {
if (num <= 1) {
return false; // Numbers less than or equal to 1 are not prime
}
for (let i = 2; i <= Math.sqrt(num); i++) {
if (num % i === 0) {
return false; // If the number is divisible by any i, it's not prime
}
}
return true; // If no divisors were found, number is prime
}
// Get user input
let user_In = prompt("Enter a number to check if it's prime:");
let num = parseInt(user_In);
if (isNaN(num)) {
console.log("Please enter a valid number.");
} else {
if (is_Prime(num)) {
console.log(`${num} is a prime number.`);
} else {
console.log(`${num} is not a prime number.`);
}
}
How This Works
- User Input: The prompt() function is used to get input from the user. This function opens a dialogue box in the browser, prompting the user to enter a value.
- Validation: After getting the user input, parseInt() is used to convert the input from a string to an integer. We also check if the input is a valid number using isNaN().
- Prime Check: The isPrime() function checks if the number is prime. It loops through possible divisors up to the square root of the number to determine if it's prime.