.Js
Function that determines whether a number is prime:
create a function to determine whether a number is prime by checking whether it's divisible by any number other than 1 and itself. Here's a JavaScript function to do that:
function isPrime(number) { // Numbers less than or equal to 1 are not prime if (number <= 1) { return false; } // Check divisibility starting from 2 up to the square root of the number for (let i = 2; i <= Math.sqrt(number); i++) { /*If the number is divisible by any number other than 1, and itself, it's not prime*/ if (number % i === 0) { return false; } } // If no divisor is found, the number is prime return true; } // Example usage: console.log(isPrime(5)); // Output: true console.log(isPrime(8)); // Output: false
true false
Explanation:
This function first checks if the number is less than or equal to 1, in which case it returns 'false' since prime numbers are defined as integers greater than 1. Then, it iterates from 2 up to the square root of the number, checking for divisibility. If the number is divisible by any integer in that range, it returns 'false'. If no divisor is found, it returns 'true', indicating that the number is prime.
What's Next?
We've now entered the finance section on this platform, where you can enhance your financial literacy.