Confused by result of modulo in Solidity - javascript

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;
}

Related

I am doing an if statement with multiples of a number

I am doing an exercise, the problem is that my if/else structure does not work properly and I do not know why.
Here is the exercise statement and my code
Your task is to write a function, fizzBuzz, that accepts a number and returns a string:
'fizz' if the number is divisible by 3;
'buzz' if the number is divisible by 5;
'fizzbuzz' if the number is divisible by both 3 and 5.
'{number}' if the number doesn't fulfil any of the above conditions.
function fizzBuzz(number) {
if (number % 3 === 0) {
return "fizz"
};
if (number % 5 === 0) {
return "buzz"
};
if (number % 3 === 0 && number % 5 === 0) {
return "fizzbuz"
};
else return number
}
Try a little mental debugging. Look at your code and run different values through it in your mind:
What happens if you run the value 6 through it?
What happens if you run the value 10 through it?
What happens if you run the value 15 through it?
Ask yourself, "How could I fix this?" (hint: order of operations is important).
Something like this would do what you expect:
function fizzBuzz(n) {
const fizz = n % 3 ? '' : 'fizz' ;
const buzz = n % 5 ? '' : 'buzz' ;
return !fizz && !buzz ? '{number}' : `${fizz}${buzz}` ;
}
or this:
function fizzBuzz( n ) {
let s;
if ( n % 3 === 0 ) {
s = 'fizz' ;
if ( n % 5 === 0 ) {
s = 'fizzbuzz' ;
}
} else if ( n % 5 == 0 ) {
s = 'buzz' ;
} else {
s = '{number}' ;
}
return s;
}
This does [at most] 2 divisions and 2 comparisions.
The former does 2 divisions and 3-4 comparisons, so it is nominally less efficient.
But I know which version I'd rather look at.
The problem is, if a number is divisible by 5 and 3 (ex 15) "fizz" would only be returned (as a factor of 3) because every block {...} terminates the function with a return (this technique is called a "short-circuit", which isn't a bad practice). So you need to put the 5 and 3 condition first. Also that condition had an undefined variable called solution so that would've been the first error. One minor thing is that each block {...} was suffixed with a semi-colon: ; which is just bad formatting but it doesn't affect functionality.
function fB(number) {
if (number % 3 === 0 && number % 5 === 0) {
return "fizzbizz";
}
if (number % 3 === 0) {
return "fizz";
}
if (number % 5 === 0) {
return "bizz";
}
return number;
}
console.log(fB(15));
console.log(fB(575));
console.log(fB(49));
console.log(fB(51));
console.log(fB(80));
console.log(fB(375));
console.log(fB(99));
console.log(fB(Infinity));

Determine a prime number function

Could anyone explain to me the 2nd and 3rd statement in the for loop
What is the 1st and 2nd i in the middle part and the last one (i = i + 6)
function prime(n) {
if (n <= 1) return false;
if (n <= 3) return true;
if (n % 2 == 0 || n % 3 == 0) return false
for (let i = 5; i * i <= n; i = i + 6) {
if (n % i == 0 || n % (i + 2) == 0)
return false;
}
return true
}
console.log(prime(11))
console.log(prime(25))
console.log(prime(29))
There are a couple of hacks in this function to determine primality of a number n.
Every non-prime number has at-least 1 factor less than or equal to its square root.
Every 6th number from 3 onwards is a multiple of 3. So, if we have already checked that 3 does not divide n, we can safely say numbers like 9,15,21... will not divide n.
The if inside the loop checks for divisibility of n by i or i + 2. Since we know, 3 | i+4 (-- from 2 above), we don't check divisibility there as it is not required. And since this loop runs from i = 5 upto i = sqrt(n), if we find no factors, we can exit the loop and return true for number's primality (-- from 1 above)

Fizzbuzz Example: What is the purpose of the equal-to operator in this example?

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.)

How does a negative value turn positive by calling it negative in the console?

i used Math.abs but I fail and found this solution, I am following on eloquent javascript and how did negative value is turned to positive, here is the code:
function isEven(n) {
if (n == 0) {
return true;
}
else if (n == 1) {
return false;
}
else if (n < 0) {
console.log(-n);
return isEven(-n); // turn -3 to 3?
}
else {
return isEven(n - 2);
}
}
console.log(isEven(-3));
Here you are a simpler test case:
> console.log( -(-3) );
3
This is not a JavaScript peculiarity, it's how maths work.
Console has nothing to do with this.
Think back to your math class. -n is a shortened expression for (-1) * n. If you multiply two negative numbers, the result is a positive number - and since you're multiplying by negative 1 (where positive 1 is identity for multiplication), the result is the same number, but positive.
Since you're checking if (n < 0) before you multiply by -1, you'll always get a positive number.
However, this is almost definitely not what you want - the code you found seems to be an example of how to use recursion to solve common problems. In real-world Javascript, you'd want something more like this:
function isEven(x)
{
return (Math.abs(x) % 2) === 0;
}
it has to be recursion
Lets break the mold! Using -1 instead of 2. Assuming an integer;
function isEven(x) {
if (x === 0) return 1; // ended
return -1 * (isEven(Math.abs(x) - 1) ? 1 : -1) === 1;
}
Other fun ways to test for even that don't need 2 or mod/remaineder
function isEven(x) {
return Math.round(Math.sin(5 * x / Math.PI)) === 0;
}
An O(log n) recursion
function isEven(x, a) {
if (!a) a = [true, false];
if (a.length > x) return a[x];
return isEven(x, a.concat(a));
}

Javascript Finding Prime Numbers

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.

Categories