Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How to make a random number divisible by 4?

Asked by 5 years ago

I already have the random part done, I just need to make sure that the number is divisible by 4. And if it is not, make it

3 answers

Log in to vote
2
Answered by 5 years ago

Simply use the modulus operator and to make it do it again until the number is divisible just use a repeat loop. Example:

local ranNum
repeat
    ranNum = math.random(1, 100)
until ranNum % 4 == 0 -- modulus returns the remainder so if the remainder is 0 you know that the number is divisible by four

I hope this helps and have a great day scripting!

0
This repeat loop could theoretically go on forever, but the odds are very low for that to happen. User#21908 42 — 5y
Ad
Log in to vote
0
Answered by
Leamir 3138 Moderation Voter Community Moderator
5 years ago
Edited 5 years ago

Hello, waffle792!

You can get % to get the modulus, and then test if it is equals to 0

print(6 % 4 == 0) -- This will print false

print(400 % 4 == 0) -- This will print true

After testing, if the number is not divisible by 4, just run the random part again, I would make it a function if I am you

Good Luck with your games

Log in to vote
0
Answered by
jakedies 315 Trusted Moderation Voter Administrator Community Moderator
5 years ago

A number is divisible by 4 if it's in the form 4k where k is any integer. Don't "keep generating random numbers" that's stupid, just generate a random integer and multiply it by 4.

Answer this question