function isPrime(num){
// loop numbers to see if any num is divisble by that number
if (num < 2){ return false
} else if (num === 2) {
return true
}
for (let i = 2; i < num; i++) {
if (num % i === 0) {
return false
} else {
return true
}
}
}
Tried changing the conditional of the for loop but still comes out as true.
Wait until the whole loop finishes before returning true, otherwise you only check the first iteration and make a decision right away whether the input is prime before checking all the rest of the numbers. Also surely you don't need to iterate the entire length of the number, Math.ceil(num/2) + 1 should suffice. This is because there's no point to ever check if anything larger than half of a number will factor into that number. (This will make a big impact on larger numbers)
function checkPrime(){
var num = document.getElementById("num").value;
var result = document.getElementById("result");
var arr=[];
if (num.length===0)
result.innerHTML = "Please, specify a number.";
else if (num<0)
result.innerHTML = "Please, specify a positive number.";
else
result.innerHTML = isPrime(num).toString();
return false;
}
function isPrime(num){
// loop numbers to see if any num is divisble by that number
if (num < 2)
return false;
else if (num === 2)
return true;
const max = Math.ceil(num/2) + 1;
for (let i = 2; i < max; i++) {
if (num % i === 0)
return false;
}
return true;
}
<form onsubmit=" return checkPrime()">
<label>Enter a number check prime</label>
<input type="number" id="num" name="num"><br>
<input type="submit" value="Submit" id="submit">
<div id="result"></div>
</form>
This means you are testing any number entered to return a bool (true/false) if it is a prime number.
I would modify your code a little bit to give this function a correct answer.
function isPrime(num){
// loop numbers to see if any num is divisble by that number
if (num < 2){
return false
}else if(num==2){
return true;
}else{
for (let i = 2; i < num; i++) {
if (num % i == 0) {
return false;
//break;
}
}
return true;
}
}
Related
const input = 3;
let isPrime = true;
outer: for(let i = 2; i < input; i++){
for(let j = 2; j < input; j++) {
if((i * j) === input) {
isPrime = false;
console.log(`${input} is Not a prime number`);
break outer;
}
}
}
if(isPrime) {
console.log(`${input} is a prime number`); }
Personally, I think this is not the right way, even though I could've done it in an easier way, I approached the problem like so.
I needed some feedback from my seniors, can I get a code review?
Nested loops are mostly time consuming solutions. If you have an other option you need to probably do that. In this case you using nested for loops to determine prime number. But you can do it with only one for loop.
const number = 3
let isPrime = true;
// check if number is equal to 1
if (number === 1) {
console.log("1 is neither prime nor composite number.");
}
// check if number is greater than 1
else if (number > 1) {
for (let i = 2; i <= Math.sqrt(number); i++) {
if (number % i == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
console.log(`${number} is a prime number`);
} else {
console.log(`${number} is a not prime number`);
}
}
For more information you can check these links:
Why nested loops are bad practice
Finding a prime number
Here's the question:
A Narcissistic Number is a positive number which is the sum of its own digits, each raised to the power of the number of digits in a given base. In this Kata, we will restrict ourselves to decimal (base 10).
For example, take 153 (3 digits), which is narcisstic:
1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153
Your code must return true or false (not 'true' and 'false') depending upon whether the given number is a Narcissistic number in base 10.
My Code is:
function narcissistic(value) {
let vLen = value.length;
let sum = 0;
for (let i = 0; i < vLen; i++) {
sum += Math.pow(value[i], vLen);
}
if (sum == value) {
return true;
} else {
return false;
}
}
But I'm getting errors. What should I do?
Numbers don't have .length, convert to string first
vLen[i], you cant treat a number as array, again, convert to string to use that syntax.
The return can be simplefied to return (sum === value);
function narcissistic(value) {
let sVal = value.toString();
let vLen = sVal.length;
let sum = 0;
for (let i = 0; i < vLen; i++) {
sum += Math.pow(sVal[i], vLen);
}
return (sum === value);
}
console.log(narcissistic(153));
console.log(narcissistic(111));
Well... There are several things wrong with this code, but I think there is mostly a problem with the types of your input.
I'll show you how you can cast the types of your input to make sure you work with the types you need:
Also... You should try to avoid using the == operator and try to use === instead (same goes for != and !==), because the == and != don't try to match the types, resulting in sometimes unpredictable results
function narcissistic(value) {
valueStr = String(value);
let vLen = valueStr.length;
let sum = 0;
for (let i = 0; i < vLen; i++) {
sum += Number(valueStr[i]) ** vLen;
}
if (sum === value) {
return true;
} else {
return false;
}
}
if(narcissistic(153)) {
console.log("narcissistic(153) is true!") // expected value: true
}
All the first 9 digits from 1 to 9 is Narcissistic number as there length is 1 and there addition is always same.
So, first we are checking weather the number is greater than 9 or not.
if(num>9) =>false than it's a narcissistic number.
-if(num>9) =>true than we have to split number into digits for that I have used x = num.toString().split('');. Which is first converting number to String and than using split() function to split it.
Than , we are looping through each digit and digitsSum += Math.pow(Number(digit), x.length); adding the power of digit to const isNarcissistic = (num) => { let x = 0; let digitsSum.
at the end, we are comparing both num & digitsSum if there are matched than number is narcissistic else not.
const isNarcissistic = (num) => {
let x = 0;
let digitsSum = 0;
if (num > 9) {
x = num.toString().split('');
x.forEach(digit => {
digitsSum += Math.pow(Number(digit), x.length);
});
if (digitsSum == num) {
return true;
} else {
return false;
}
} else {
return true;
}
}
console.log(isNarcissistic(153));
console.log(isNarcissistic(1634));
console.log(isNarcissistic(1433));
console.log(isNarcissistic(342));
how come the following is not accurately logging whether a number is prime or not?
function isPrime2(num) {
for(let i = 2; i < num; i++) {
if(num % i === 0) {
return console.log(false); break;
} else{return console.log(true)}
}
}
isPrime2(33)returns true, even though it is a prime number.
If i = 2, then the console will log true since 33/2 = 16.5
But since the loop isn't over, the next i value is i=3,
so shouldn't the console log false and then break out of the loop completely, leaving the final answer to be false?
There are two problems here.
Your logic is broken
function isPrime2(num) {
for (let i = 2; i < num; i++) {
const remainder = num % i;
console.log({
remainder
});
if (remainder === 0) {
return console.log(false);
break;
} else {
return console.log(true)
}
}
}
isPrime2(33);
i starts at 2.
if(num % i === 0) is false, so we go to else
else{return console.log(true)} causes it to log true and exit the function.
Your failure condition is triggered when the first test fails instead of waiting for the loop to finish with a success condition for any of the tests.
33 is not a prime
It is divisible by 3 and 11.
function isPrime2(num) {
for (let i = 2; i < num; i++) {
const remainder = num % i;
console.log({
remainder
});
if (remainder === 0) {
return console.log(false);
break;
}
}
return console.log(true)
}
isPrime2(33);
I am trying to solve this problem where I need to print true or false on the console depending on the number (true if a number is Prime and false if it is not). I seem to have the solution but I know there is a mistake somewhere because I get different answers if I change the boolean values of the 2 isPrime variables.
Here is the question:
Return true if num is prime, otherwise return false.
Hint: a prime number is only evenly divisible by itself and 1
Hint 2: you can solve this using a for loop.
Note: 0 and 1 are NOT considered prime numbers
Input Example:
1
7
11
15
20
Output Example:
false
true
true
false
false
My code:
function isPrime(num){
let isPrime = '';
for(let i = 2; i <= Math.sqrt(num); i++){
if(num % i === 0){
isPrime = false;
} else {
isPrime = true;
}
}
return isPrime;
}
isPrime(11);
You are very close. I will build on top of your solution. You need to return false as soon as you detect that the number is not prime. This avoids us making additional redundant calculations.
You also did not take into account the first hint.
Hint - Note: 0 and 1 are NOT considered prime numbers
For this you can simply return false if number is 0 or 1.
function isPrime(num) {
if (num === 0 || num === 1) return false;
for (let i = 2; i <= Math.sqrt(num); i++) {
if (num % i === 0) return false;
}
return true;
}
Also in your code you are using a variable isPrime to keep track of boolean values while initialising it with an empty string. This is not correct. Javascript allows this because it's weakly typed, but this is misleading. So in future if you define a variable for boolean value don't initialise it with a string ;)
To address your comment further. If you do want to stick with having a flag in your code, then you can initialise isPrime with true instead of an empty string.
That way you can get rid of the else part in the for loop, making the code shorter. I used code provided by #Commercial Suicide (by the way he did say that there are more elegant solutions) as an example:
function isPrime(num) {
let flag = true;
let isPrime = true;
if (num === 0 || num === 1) return false;
if (num === 2) return true;
for (let i = 2; i <= Math.sqrt(num); i++) {
if (flag) {
if(num % i === 0) {
isPrime = false;
flag = false;
}
}
}
return isPrime;
}
const numbers = [1, 7, 11, 15, 20];
const booleans = [false, true, true, false, false];
numbers.forEach((item, i) => {
if (isPrime(item) === booleans[i]) {
console.log("CORRECT");
} else {
console.log("WRONG");
}
})
You can then go a step further and remove the flag variable.
function isPrime(num) {
let isPrime = true;
if (num === 0 || num === 1) return false;
if (num === 2) return true;
for (let i = 2; i <= Math.sqrt(num); i++) {
if (isPrime) {
if(num % i === 0) {
isPrime = false;
} else {
isPrime = true;
}
}
}
return isPrime;
}
But now it should become even more clear that those flags are actually redundant, as I pointed out initially. Simply return false as soon as you detect that the number is not prime to avoid further unnecessary loop runs. From my experience in javascript over the years I can see that we are heading towards functional programming mindset. It helps to avoid variable mutations generally.
It's because your isPrime variable can be overriding many times, simple flag (for example) will prevent this issue. I have also added check for 0, 1 and 2. There are more elegant ways to do that, but I wanted to keep your logic, here is an example with some tests:
function isPrime(num) {
let flag = true;
let isPrime = '';
if (num === 0 || num === 1) return false;
if (num === 2) return true;
for (let i = 2; i <= Math.sqrt(num); i++) {
if (flag) {
if(num % i === 0) {
isPrime = false;
flag = false;
} else {
isPrime = true;
}
}
}
return isPrime;
}
const numbers = [1, 7, 11, 15, 20];
const booleans = [false, true, true, false, false];
numbers.forEach((item, i) => {
if (isPrime(item) === booleans[i]) {
console.log("CORRECT");
} else {
console.log("WRONG");
}
})
I'm a beginner and trying to complete a prime number test but I'm running into an issue. Here is what I have:
var n = Number(prompt("Input the number you want to check for prime:"));
var i;
if (n < 2) {
alert(n + " is not a prime number.");
}
for (var i = 2; i <= Math.sqrt(n); i++) {
if (n % i === 0) {
alert(n + " is not a prime number.");
break;
}
else {
alert(n + " is a prime number.");
break;
}
}
It's running correctly except an alert won't pop up if I input 3 or 2 and any number with a 3 in it is coming back as a prime number even if it isn't. Other than that all of my tests have worked.
Ahhh, your problem is the way you've structured the loop. You're breaking out regardless of if the check's completed.
var n = Number(prompt("Input the number you want to check for prime:"));
var i;
var isPrime = true;
if (n < 2) {
isPrime = false;
} else if (n < 4 && n >= 2) {
// isPrime is already true
} else if (n % 2 === 0) {
isPrime = false; // no divisor of 2 can be prime
} else {
var sqrtN = Math.sqrt(n);
for (var i = 3; i <= sqrtN; i = i + 2) {
if (n % i === 0) {
// Only break out of the loop if a match is found
isPrime = false;
break;
}
}
}
if (isPrime) {
alert(n + " is a prime number.");
} else {
alert(n + " is not a prime number.");
}
Or, a perhaps more organized solution:
function isPrime (n) {
n = parseInt(n);
var i;
if (Number.isNaN(n)) {
return false;
} else if (n < 2) {
// 1 is not prime
return false;
} if (n < 4) {
// 2 and 3 are prime, so why not skip checking them?
return true;
} else if (n % 2 === 0) {
// No number divisible by 2 is prime.
return false;
} else {
// This won't change, so calculate it once as suggested by Weather Vane.
var sqrtN = Math.sqrt(n);
// 4, 6, 8... All divisible by 2, and would be caught by initial check.
for (i = 3; i < sqrtN; i = i + 2) {
// Not a prime if it's evenly divisible.
if (n % i === 0) {
return false;
}
}
// Otherwise prime.
return true;
}
}
Of course. If n % i is not 0, it means that i does not divide n, but it does not mean n is prime. You must check all i in order to say that.
Moreover, don't recalculate expensive Math.sqrt(n) at each iteration. And be aware of NaN.
var n = Number(prompt("Input the number you want to check for prime:"));
function isPrime(n) {
if (n < 2 || !n) return false;
for (var i = 2; i*i <= n; i++) {
if (n % i === 0) return false;
}
return true;
}
alert(n + " is " + (isPrime(n) ? "" : "NOT ") + "a prime number.");
Of course, this algorithm is exponential (pseudo-polynomial). Don't use it for big n. Instead, see e.g. Miller–Rabin primality test or AKS primality test, which are polynomial.
var UI = window.prompt("Enter a whole number to test as a prime number: \n", "0");
var TV = parseInt(UI, 10);
var HITS = 0;
var DD = TV;
while (DD > 0) {
if (TV % DD === 0) {
HITS++;
}
DD--;
}
if (HITS > 2) {
document.write(UI + " is a NOT prime number");
} else {
document.write(UI + " is a prime number");
}
Please have reference to old questions asked in stackoverflow
link to the old question