I'm trying to code a script to test whether a user-inputted number is prime or not. I'm coding several different primality tests, but one in particular is giving me a hard time.
function isPrimeSix() {
var numberPrimeSix = document.getElementById("primeSixInput").value;
var loopCount = 0;
for (var i = 1; i < Math.floor((numberPrimeSix / 6) + 1) + 1; i++)
{
if (numberPrimeSix === (6 * i) + 1)
{
//Irrelevant code here//
}
else if (numberPrimeSix === (6 * i) - 1)
{
//More irrelevant code//
}
else
{
loopCount++
}
};
if (numberPrimeSix === 2 || numberPrimeSix === 3 || numberPrimeSix === 5 || numberPrimeSix === 7)
{
alert(numberPrimeSix + " is prime.");
}
else if (prime === false || loopCount === Math.floor((numberPrimeSix / 6) + 1))
{
alert(numberPrimeSix + " is not prime.");
}
else if (prime === true)
{
alert(numberPrimeSix + " is prime.");
}
else
{
alert("Error");
};
}
Every time the for loop goes around, the embedded if statement will not evaluate, even if for that particular value of i one of the statements is true. Regardless of what number is assigned to numberPrimeSix, the script will always go to the else section of the loop, meaning that an alert will pop up telling me that the number is not prime (because the value of loopCount is equal to the value defined by the last if statement).
Can anyone tell me why this is? I hope this makes sense, and if the 'irrelevant code' is needed I'll provide it. Thanks!
A string will never be exactly equal (===) to a number. In JavaScript, if you use ==, the operands will be converted to be the same type before comparing. If you instead use ===, that step will be skipped and instead they will be tested for strict equality, meaning same type and value, not just same value.
You have two options. Replace === with ==, or, convert the value before the loop and continue using strict equal. It will be much faster to convert the value before the loop so that you're not converting it over and over with each iteration.
var numberPrimeSix = parseInt(document.getElementById("primeSixInput").value, 10);
more reading: Which equals operator (== vs ===) should be used in JavaScript comparisons?
Related
I am learning basic conditionals and i'm not 100% sure on why the && in this case is returning 'false' in console.
Is it because the variable is not both 0 and 1.
Thank you in advance,
let i = 1;
if (i == 0 && i == 1) {
console.log('true');
} else {
console.log('false');
}
I was expecting true.
Even if I set var i = 01; it still shows false.
I just need a simple explanation why to get it clear in my head :)
i is not equal to 0, therefore the logical AND expression immediately fails; the else block is then evaluated, printing false.
If you change AND to OR, the code will work as you probably expect.
let i = 1;
if (i == 0 || i == 1) {
console.log('true');
} else {
console.log('false');
}
For an AND (&&) expression to evaluate to true, both sides of the expression need to be true.
For an OR (||) expression to evaluate to true, one or both side(s) of the expression need(s) to be true.
For an XOR (JS does not have a logical XOR operator) expression to evaluate to true, one and only one side of the expression needs to be true.
Note: in JS, never attempt to write a number literal with a leading zero. This is because in non-strict mode environments such numbers are interpreted as octal numbers; in strict-mode environments you'll get an error.
How would i be able to be two values at once? Even if you did something like const i = [0, 1] it would still return false.
i = 01
Why would this work? The only way this would work is if you made it a string, split it, assigned it to two different variables, and then ran the check against those two variables.
Perhaps you are thinking of the OR operator ||.
let i = 1;
if (1 === 0 || i === 1) {
return true;
} else {
return false;
}
Or even use ternaries, which are, from looking at this question, way beyond your skill:
let i = 1;
const j = i === 0 || i === 1 ? true : false;
console.log(j);
I'm making a calculator for a site project of mine where you can type your entire expression before resolving, for example: 2+3*4 would return 14, 22-4 would return 18, 20+5! would return 140, and so on.
And that works for simple expressions like the ones I showed, but when I add brackets the code breaks.
So a simple expression like (2+3)! that should return 120 actually returns 10 or 2+3!.
my original ideia to make even the basic 2+3! work was to separate the string in math simbols and the rest. so it would separate in this case it would separate it into 2, + and 3!; where it would find the symbol and resolve just that part. And that's why it solves 10 instead of not working.
But after trying to solve I couldn't make the code work except in a extremely specific situation, so I decided to redo the code and post this here in case someone could help me out.
This is the function that I'm currently using to prepare my string for evaluation:
function sepOperFat(){
//2+3! it's working
//1+(2-(2+2)+3)! want that to work in the end
var value = document.calculator.ans.value;
var operandoPos = ['0'];
var operandoInPos = [''];
var paraResolver = [];
for(i = 0; i <= value.length; i++){
//check if value[i] is equal to +, -, ×, ÷, * & /
if(value[i] == '+' || value[i] == '-' || value[i] == '×' || value[i] == '÷' || value[i] == '*' || value[i] == '/'){
operandoPos.push(i);
operandoInPos.push(value[i]);
}
}
paraResolver.push(value.slice(operandoPos[0], operandoPos[1]));
for(var total = 1; total <= operandoPos.length; total++){
paraResolver.push(value.slice(operandoPos[total] + 1, operandoPos[total + 1]));
}
document.calculator.ans.value = '';
for(var total = 0; total <= paraResolver.length - 2; total++){
if(paraResolver[total].includes('!')){
document.calculator.ans.value += "factorial(" + paraResolver[total] + ")";
}else{
document.calculator.ans.value += paraResolver[total];
}
document.calculator.ans.value += operandoInPos[total + 1];
}
}
document.calculator.ans.value is the name of the string where i have the expression.
operandoPos is the position on the string where a symbol is at.
operandoInPos is the symbol (I maybe could have used value.charAt(operandoPos) for that too).
paraResolver is the number that I will be solving (like 3).
factorial( is the name of my function responsible for making the number factorial.
the function doesn't have a return because I still want to solve inside the document.calculator.ans.value.
to resolve the equation I'm using document.calculator.ans.value = Function('"use strict"; return '+ document.calculator.ans.value)(); that activates when I press a button.
And yeah, that's it. I just want a function capable of knowing the difference between (2+3)! and 2+(3)! so it can return factorial(2+3) instead of (2+factorial(3)).
Thank you for your help.
Your biggest problem is going to be that order of operations says parentheses need to be evaluated first. This might mean your code has to change considerably to support whatever comes out of your parentheses parsing.
I don't think you want all of that handled for you, but an approach you can take to sorting out the parenthesis part is something like this:
function parseParentheses(input) {
let openParenCount = 0;
let myOpenParenIndex = 0;
let myEndParenIndex = 0;
const result = [];
for (let i = 0; i < input.length; i++) {
if (input[i] === '(') {
if (openParenCount === 0) {
myOpenParenIndex=i;
// checking if anything exists before this set of parentheses
if (i !== myEndParenIndex) {
result.push(input.substring(myEndParenIndex, i));
}
}
openParenCount++;
}
if (input[i] === ')') {
openParenCount--;
if (openParenCount === 0) {
myEndParenIndex=i+1;
// recurse the contents of the parentheses to search for nested ones
result.push(parseParentheses(input.substring(myOpenParenIndex+1, i)));
}
}
}
// capture anything after the last parentheses
if (input.length > myEndParenIndex) {
result.push(input.substring(myEndParenIndex, input.length));
}
return result;
}
// tests
console.log(JSON.stringify(parseParentheses('1!+20'))) // ["1!+20"]
console.log(JSON.stringify(parseParentheses('1-(2+2)!'))) // ["1-",["2+2"],"!"]
console.log(JSON.stringify(parseParentheses('(1-3)*(2+5)'))) // [["1-3"],"*",["2+5"]]
console.log(JSON.stringify(parseParentheses('1+(2-(3+4))'))) // ["1+",["2-",["3+4"]]]
this will wrap your input in an array, and essentially group anything wrapped in brackets into nested arrays.
I can further explain what's happening here, but you're not likely to want this specific code so much as the general idea of how you might approach unwrapping parenthesis.
It's worth noting, the code I've provided is barely functional and has no error handling, and will behave poorly if something like 1 - (2 + 3 or 1 - )2+3( is provided.
I already know this wouldn't work If I passed something like 0 or 1, but why wouldn't it work If it managed to work with 2 and 7.
I'm still new to Javascript programming so I'm just trying to figure out why adding
if(number = number % 2 == 0) or the other wouldn't work.
Here's the code:
function even_or_odd(number) {
if(number = number % 2 == 0) {
return "Even"
}else if(number = number % 2 !== 0) {
return "Odd"
}
};
= is an assignment operator. It assigns the value of the expression on the right-hand side to a variable on the left-hand side.
== is an equality operator. It tests the equality of the result of both the left and right-hand-side expression.
Since you're using = and inadvertently assigning number to the value of your expression on the right, it will always evaluate to a truthy value and return "Even". To fix, remove the number = from each of the expressions:
function even_or_odd(number) {
if(number % 2 == 0) {
return "Even"
}else if(number % 2 !== 0) {
return "Odd"
}
};
console.log(even_or_odd(0));
console.log(even_or_odd(1));
MDN has a great section on this in their if...else page:
It is advisable to not use simple assignments in a conditional expression, because the assignment can be confused with equality when glancing over the code. For example, do not use the following code:
if (x = y) {
/* do something */
}
If you need to use an assignment in a conditional expression, a common practice is to put additional parentheses around the assignment. For example:
if ((x = y)) {
/* do something */
}
I have an if statement that is supposed to execute code if a variable returns false, but even though I have checked and made sure the variable returns false, the code does not execute. Here is the code:
SOLUTION: i seem to have accidentally misplaced the if statement, and have moved it and fixed the program. thank you everyone who has helped me fix my problem
function letterCheck() {
var wordToGuess = puzzle;
var letterToGuess = guess;
console.log(letterToGuess);
matched = false;
for (x = 0; x < wordToGuess.length; x++) {
if (letterToGuess === wordToGuess[x]) {
console.log('Your guess was correct!');
console.log('You have', 6 - parts, 'incorrect guesses remaining');
blanks[x] = letterToGuess;
console.log(blanks);
var fillBlank = '';
for (y = 0; y < blanks.length; y++) {
fillBlank += blanks[y];
}
document.getElementById('puzzle').innerHTML = fillBlank;
matched = true
win++
if (win === puzzle.length) {
setTimeout(() => alert("You win!"), 100)
}
break;
}
}
}
//this is the if statement that is not working
if (this.matched === false) {
console.log("Your guess was incorrect!");
parts++;
graphics[parts - 1]();
console.log('You have', 6 - parts, 'incorrect guesses remaining');
}
"matched" and "this.matched" are 2 different variables. "matched" is global, "this. matched" is local to the function.
To fix: Use either of "matched" or "this.matched" everywhere - don't mix and match.
Some basic questions need to be asked first. What programming language are you using?
I will assume that you are using JavaScript, because that is the only language that comes to mind that has a === operator. The identity operator === behaves identically to the equality operator == except no type conversion is done. The identity operator requires that all types must be the same types to be considered equal.
Therefore, the == equality operator will compare for equality after doing any necessary type conversions, while the === identity operator will not do the conversion, so if two values are not the same type, the identity operator will simply return false.
Both operators execute at approximately the same speed, so if I were you, I would switch to the equality operator and try again. Let me know what you get!
Reference: http://www.c-point.com/javascript_tutorial/jsgrpComparison.htm
This question already has answers here:
Why doesn't my simple if-statement render false in javascript?
(2 answers)
Closed 6 years ago.
I'm trying to check if a string is blank, less than or equal to 9 digits, or up to 10 digits. But it always follows the else if (str.length <= 9).
if (str = ''){
console.log("The string cannot be blank");
} else if (str.length <= 9) {
console.log("The string must be at least 9 characters long");
} else if (str.length <= 10) {
console.log("The string is long enough.");
}
No matter what I put in, I always get The string must be at least 9 characters long. Why?
= is always assignment. Equality comparison is == (loose, coerces types to try to make a match) or === (no type coercion).
So you want
if (str === ''){
// -----^^^
not
// NOT THIS
if (str = ''){
// -----^
What happens when you do if (str = '') is that the assignment str = '' is done, and then the resulting value ('') is tested, effectively like this (if we ignore a couple of details):
str = '';
if (str) {
Since '' is a falsy value in JavaScript, that check will be false and it goes to the else if (str.length <= 9) step. Since at that point, str.length is 0, that's the path the code takes.