I am writing a little script to find and print out all the prime numbers from X thru Y. Here is what I have written:
var numX = prompt('Enter a number greater than 0:','');
var numY = prompt('Enter a number greater than ' + numX + ':','');
while (numX <= numY) {
if (numX == 1 || numX == 2 || numX == 3) {
document.write(numX + '</br>');
} else if (numX % 2 === 0 || numX % 3 === 0 || numX % 5 === 0 || numX % 7 === 0){
document.write();
} else {
document.write(numX + '</br>');
}
numX++;
};
Now, this works just fine so long as the first number is 1. If, however, the first number is anything greater than 1 it does not print out anything. I am not sure if this is the right forum for this question (perhaps a math forum?), but I thought I would ask here on the off chance someone could help me out. I also know that a sieve is the better way to go about this, but I wanted to try and figure this out as a while loop first. Any and all help is appreciated!
While I understand what you are trying to do, I highly recommend taking a look at the Sieve of Eratosthenes. You really want to get the hang of knowing different algorithms to compute these things in case you decide to deal with really large numbers. While the way you go about it now might work in smaller ranges, bigger ranges are going to go crazy.
Also I believe this Stackoverflow question is very similar to this one and the answer for it is very well made:
finding sum of prime numbers under 250
You can try any of the options here : http://www.javascripter.net/faq/numberisprime.htm
Hi i have added bit change to ur code (added condition for 5 and 7 prime numbers) and its working...
var numX = prompt('Enter a number greater than 0:','');
var numY = prompt('Enter a number greater than ' + numX + ':','');
while (numX <= numY) {
if (numX == 1 || numX == 2 || numX == 3 || numX == 5 || numX == 7) {
document.write(numX + '</br>');
} else if (numX % 2 === 0 || numX % 3 === 0 || numX % 5 === 0 || numX % 7 === 0){
document.write();
} else {
document.write(numX + '</br>');
}
numX++;
};
Check the demo here
OK, turns out that I jumped the gun on asking this question. I was more concerned with getting the else if statement working that I failed to even note that my formula was seriously flawed!
The issue possibly could be with the second variable. If the first variable is 1 then the second variable can be any number. However, if the first variable is greater than 1 then the second variable has to be less than 100 or it will not work.
Related
Just going through some learning pains and wanted to know if anyone could help.
My current goal on the course I'm on is to return a bool value from a function depending on if the 2nd uint divides evenly into the first uint.
I have the correct false logic in place according to the site but it still fails on the true logic.
This is the current function I have created
function dividesEvenly(uint x, uint y) public pure returns(bool) {
if (y % x == 0) {
return true;
} else if (y % x != 0) {
return false;
}
}
One of the test cases is (4,2) which I input into it myself mainly and it does chuck out a false. However doing 4 % 2 provides 0 which should return true so I'm not entirely sure what I've done wrong here.
Any help appreciated.
The modulo operation in your snippet is reversed - y % x. So instead of 4 % 2 (result 0), it calculates 2 % 4 (result 2).
Solution: Reverse back the arithmetics
// the reminder after dividing 4 by 2 is 0
// 4 % 2 == 0
if (x % y == 0) {
return true;
}
I know there are easier and quicker ways to write this program. However, I'm having trouble understanding why the equal-to operator is needed here? Referring to the == 0 instances below.
for(let x=1;x<101;x++) {
if(x % 3 == 0 && x % 5 == 0){
console.log('fizzbuzz')
} else if(x % 3 == 0) {
console.log('fizz')
} else if(x % 5 == 0) {
console.log('buzz')
} else {
console.log(x)
}
}
x % 3 == 0 is checking to see if x is evenly divisible by three. If it isn't, then there will be a non-zero remainder. (The x % 3 part of that expression uses the % operator to get the remainder after division.)
I'm starting to learn javascript for front-end programming, being python my first language to learn completely.
So I'm trying to solve a while loop excersise that console-logs every number from 50-300 that is divisble by 5 and 3.
So in python i would do this:
i = 50
while i < 301:
if i % 5 == i % 3 == 0:
print(i)
i += 1
And works flawlessly. I know you could use and and operator but the whole point of this question is to avoid using it.
So I try the same thing in javascript
var i = 50;
while (i < 301){
if (i % 5 === i % 3 === 0){
console.log(i);
}
i ++;
}
And somehow that wont work. However, with an && operator it does. Are double equalities in javascript not allowed? If they are, what am I missing?
It's allowed, and it does exactly what you told it to do -- it's just that that's not the same as what you want it to do. i % 5 === i % 3 === 0 is the same as (i % 5 === i % 3) === 0 (because === is left-associative). (i % 5 === i % 3) evaluates to either true or false depending on the value of i, and true === 0 and false === 0 are both false, so the condition will always be false.
I've encountered some misundertanding. There is a for cycle with some if statements:
for (var number = 1; number < 100; number++) {
if (number % 3 == 0 && number % 5 == 0)
console.log(number + "fizzbuzz");
if (number % 5 == 0)
console.log(number + " buzz");
if (number % 3 == 0)
console.log(number + " fizz");
else console.log(number);
}
The output of this code is 1, 2, 3 fizz, 4, 5 buzz, etc. So it's what expected.
But if we delete braces the output will be like this:
15fizzbuzz
30fizzbuzz
45fizzbuzz
60fizzbuzz
75fizzbuzz
90fizzbuzz
100 buzz
100
Also, there is a second implementation of this program(with the right-way if-else statements):
for (var number = 1; number < 100; number++)
if (number % 3 == 0 && number % 5 == 0)
console.log(number + "fizzbuzz");
else if (number % 5 == 0)
console.log(number + "buzz");
else if (number % 3 == 0)
console.log(number + "fizz");
else console.log(number);
Notice that there are no braces too, but the output is ok.
Can you explain, what's the difference?
When you miss a semicolon or brackets, javascript tries to insert it on its own, & at times can produce some weird results like this. (Which is correct by the rules, just humans & machine don't agree on how to process it :D )
When you remove braces of for loop javascript tries to puts braces in code & run it, this is different that how you expect it to behave thus you are confused!
What you wrote & read:
for (var number = 1; number < 100; number++)
if (number % 3 == 0 && number % 5 == 0)
console.log(number + "fizzbuzz");
if (number % 5 == 0)
console.log(number + " buzz");
if (number % 3 == 0)
console.log(number + " fizz");
else console.log(number);
What javascript did with it & executes:
for (var number = 1; number < 100; number++){ //runs loop here
if (number % 3 == 0 && number % 5 == 0){
console.log(number + "fizzbuzz"); //prints for first condition
}
}
//now number is 100!
if (number % 5 == 0){
console.log(number + " buzz"); //prints for second condition once cause 100%5==0 is true
}
if (number % 3 == 0){
console.log(number + " fizz");
}
else{
console.log(number); //prints for this else condition once cause 100%3==0 is false
}
Which is perfectly valid & there is no error or bug here!
This happens because if the is no immediate else after if then javascript terminate that statement there, but if you use else...if then it continues that statement till if find a else or a statement not followed by else
If you want to play with this type of behaviour use Google Closure Compiler to see how code is interpreted by machine.
NOTE: As #carcigenicate suggest in comments, Always use braces!
As a lot of comments pointed out, its the lack of elses ( or blocks ) in your first code that make it going wrong.
//a bit shortified to make it clearer
var a=true,b=true;
if(a && b){ }// will be executed
if(a){ } //will be executed
if(b){} //will be executed
//vs.
if(a&&b){}//will be executed
else if(a){}//else => not executed
else if(b){}//else => not executed
However, it might be better to restructure your code as its quite repetitive:
for (var number = 1; number < 100; number++)
console.log(number+ (number % 3 == 0?"fizz":"")+ (number % 5 == 0?"buzz":""));
So log the number, if its a multiple of 3 add "fizz" and if its an multiple of 5 add "buzz"...
The syntax of a for loop is for (statementA; statementB; statementC) statementD. Statements can be grouped together with {}, so {statement, statement, ...} can be used where a single statement is expected.
for (var number = 1; number < 100; number++) {
if (number % 3 == 0 && number % 5 == 0)
console.log(number + "fizzbuzz");
if (number % 5 == 0)
console.log(number + " buzz");
In this case statementA is var number = 1, statementB is number < 100, and statementC is number++ and statementD is if (number % 3 == 0 && number % 5 == 0) console.log(number + "fizzbuzz"). The second if is another statement that does not belong to the for loop. If you want for the second if statement to belong to the for loop, you need to use {} to group the statements together.
The syntax of a if statement is if (expression) statement or if (expression) else statement. Using several if else aligned you are able to pass the first statement to the for loop, the second statement is going to belong to the first if that still belongs to the for loop. That is why the last example works without {}.
It is important to note that the code may work, but it is still bad code. It is recommended to use {} to group the statement from below for for, while, and if even if it is a single statement.
You may want to learn the JavaScript syntax before trying to understand JavaScript code. https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps
I have the following rather verbose conditional, I'm trying to wrap my head around a simpler version but I'm not getting anywhere.
if( agent % $.settings.gridSize === 0 && value % $.settings.gridSize == 1 ){
// Dud
}else if(agent % $.settings.gridSize == 1 && value % $.settings.gridSize === 0){
// Dud
}else{
freeCells.push(value);
}
Is there a way I can achieve the same condition with a single if statement, rather than using the throw-away if else?
Something like:
if(!(a && b) && !(x && y)){
// Do stuff
}
Yes, it's possible and you've (almost) answered your question yourself.
You can do the following:
var gS = $.settings.gridSize;
if(!(agent % gS === 0 && value % gS == 1) && !(agent % gS == 1 && value % gS === 0)) {
freeCells.push(value);
}
Depending on the possible values of $.settings.gridSize etc., it's possible that what you are looking for is:
if (agent % $.settings.gridSize !== value % $.settings.gridSize) {
// Dud
} else {
which also makes the semantics clearer: the modulo involving agent should be "different" (in the 0/1 sense) from the module involving value.
if (
agent % $.settings.gridSize > 1
||
(agent + value) % $.settings.gridSize !== 1
) {
freeCells.push(value);
}
I think it's pretty self-explaining.
Edit
Seems like it isn't that self-explaining actually.
I made a few assumptions for the transformation.
// Dud means to do nothing.
$.settings.gridSize is a positive integer, henceforth referred to as gridSize.
agent and value are non-negative integers.
For a value not to be pushed agent % gridSize has to be either 0 or 1. Since there are no negative numbers or fractional parts involved this means the same as agent % gridSize <= 1. So if the remainder is greater than 1 then value gets pushed.
Otherwise agent % gridSize is either 0 or 1. And for the value not to be pushed value % gridSize has to take on the respective other value. In total this would mean that (agent + value) % gridSize === 1. So if it's not 1 then value gets pushed.