'Checking the last digit of an integer value in JavaScript/p5
So I'm coding something in p5.js to check whether a number is prime or not. Here's the function:
function prime(n) {
let P = true;
for (let i = 2; i <= sqrt(n); i++) {
if (n%i == 0) {
P = false; break;
} else {
P = true; break;
}
} return P;
}
Everything works fine, except for the i <= sqrt(n) and if(n%i == 0) bits...
The % operator gives you the remainder of a/b, but when i type in:
prime(integer that ends with 5)
into the console, it returns true, when it should return false.
So I want to add a codtition that if the last digit of n is 5, return false. how do I do that?
Thanks!
Solution 1:[1]
Here is the working code for prime number
function prime(n) {
var sqrtnum=Math.floor(Math.sqrt(n));
var prime = n != 1;
for(var i=2; i<sqrtnum+1; i++) { // sqrtnum+1
if(n % i == 0) {
prime = false;
break;
}
}
return prime;
}
Solution 2:[2]
Just remove break keyword in the else part of your code .
function prime(n) {
let P = true;
for (let i = 2; i <= Math.sqrt(n); i++) {
if (n%i == 0) {
P = false; break;
} else {
P = true;
}
} return P;
}
console.log(prime(25)?"prime":"not prime")
Solution 3:[3]
There are many optimisations you could implement here. For example you could exclude all even numbers from your testing loop. This is only a start. The sieve of Erastostenes provides guidance on further improvements.
function prime(n) {
if (!n%2) return false;
for (let i=3;i<=Math.sqrt(n); i+=2)
if (n%i == 0) return false
return true
}
[47,48,1005,234,239].forEach(n=>
console.log(n,prime(n)))
In this variation of the script the number is actually decomposed into its prime number divisors:
function decomp(n) {
const comp=[];
if (n%2==0) return [2,...decomp(n/2)];
for (let i=3;i<=Math.sqrt(n); i+=2)
if (n%i==0) return [i,...decomp(n/i)];
return [n];
}
function notPrime(n){
const comps=decomp(n);
return comps.length>1?comps:false;
}
[47,48,1005,1001,234,239,4968417].forEach(n=>
console.log(n,notPrime(n)))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Asim Khan |
| Solution 2 | Dharman |
| Solution 3 |
