Math Question for people who like Math

Ok, so I got a Value of 62. normally you cant evenly divide 62 by 4.

What would I have to do to make any whole number Dividable by 4?

1 Like

64 divided by 4 equals 16 does this help

1 Like

I’d use the modulo operator. Read up on that. It gives a remainder which can be added back to the original.

4 Likes

not really, I’m trying to input any whole number like 3 and some how evenly divide it by 4.

Roblox can evenly divide numbers, but if you need so, you can try to make the number go up by one until it is divisible like this:

local myNumber = math.random(1, math.random(1, math.random(math.random(1,1000000000), math.random(1,1000000000))))
print(myNumber)

while wait() do
	if myNumber / 4 ~= math.ceil(myNumber / 4) then
		myNumber = myNumber + 1
	else
		print("Successful match found.")
		print(myNumber)
		print(myNumber / 4)

		break
	end
end

-- If you want it to round up or down then use the respect ceiling or floor function in math.
3 Likes

Thanks a lot, this will make what I’m doing much more efficient :slight_smile:

1 Like

Np, if you have any problems or need more help, my dms are open.

Well this is how I would do it,

You can simply do this:

local myNumber = 62
local roundedDown = myNumber - (myNumber%4)
local roundedUp = myNumber + (myNumber%4)
-- Works with any numbers.
print(roundedDown) -- 60
print(roundedUp) -- 64

In case it is a decimal you can just do

local myNumber = 62.5352
myNumber = math.floor(myNumber)
-- The rest of the thing I said before
1 Like

math.floor(n/d + 0.5) * d

Example: math.floor(62/4 + 0.5) * 4

Function form
local function nearestDivisibleBy(n, d)
    return n == 0 and n or math.floor(n/d + 0.5) * d
end
-- return 0 if n is 0, this would prevent dividing by 0 unless you purposely don't want 0 to be returned in this edge case
1 Like

That’s a very bruteforce way to do the thing you wanted, it would computationally be intensive if you had to search for the nearest divisible number when your divisor is a large number.

I won’t be against you if you want to use that method but just consider using a function designed to find the solution without having to do possibly many iterations like a loop by doing something that finishes the job in one run.

Your right. I hate to change the solution, but your answer is the most efficient out of all the replies.

1 Like

:+1:

Avoiding loop methods when possible will always let you have a more efficient method.

1 Like