From Test-Scratch-Wiki

(Redirected from Eng:() Mod ())

() Mod ()
2.0 () Mod ().png
Category Operator
Type Reporter

The () Mod () block ("mod" is short for "modulo") is an Operators block and a Reporter block. The block reports the remainder of the division when the first value is divided by the second. For example, when 10 is put in the first input and 3 in the second, the block will report 1; 10 divided by 3 gives a remainder of 1.

Negative numbers behave a little differently, because a remainder must always be positive. -10 mod 3 equals 2, not -1, because you have to multiply 3 by -4 to have any remainder at all.

Example Uses

If a project is doing divisibility tests, the () Mod () block can be of use.

Some common uses for the () Mod () block:

  • Checking if two numbers divide without a remainder
if <((a) mod (b)) = [0]> then
   say [a is divisible by b]
else
   say [a is not divisible by b]
end
  • Checking if a number is a whole number
if <((a) mod (1)) = [0]> then
   say [a is a whole number]
else
   say [a is not a whole number]
end
  • Checking if numbers are odd or even
if <((a) mod (2)) = [0]> then
   say [a is an even number]
else
if <((a) mod (1)) = [0]> then
   say [a is an odd number]
else
   say [a is not an integer]
end
end
  • Repeatedly iterating through a list:
when gf clicked
set [x v] to [0]
forever
change [x v] by (1)
say (item (x) of [list v])
set [x v] to ((x) mod (length of [list v]))
  • Reusing background-sprites when scrolling
when gf clicked
forever
set x to (((x position) + (240)) mod (480))

Workaround

Main article: List of Block Workarounds

If only positive numbers are wanted, the block can be replicated with the following code (the variable remainder is the reported value):

if <(round ((a) / (b))) > ((a) / (b))> then
set [remainder v] to ((a) - ((round (((a) / (b)) - (0.5))) * (b)))
else
set [remainder v] to ((a) - ((round ((a) / (b))) * (b)))
end

Negative values are rarely used in the () Mod () block, although it is possible. The output given when a negative value is in the first insert and a positive value is in the second is the positive value, so if the negative value is wanted, you must subtract the number in the second insert from the remainder, as so:

if <(a) < (0)> then
if <(b) > (0)> then
set [remainder v] to (((a) mod (b)) - (b))
else
set [remainder v] to ((a) mod (b))
end
else
set [remainder v] to ((a) mod (b))

See Also

Cookies help us deliver our services. By using our services, you agree to our use of cookies.