Hello there, Im trying to make a function that give me the largest number of multiples of the first number (x), and it must be less than the second number(y) for positive numbers and more for negative numbers
exemples:
x = 10
y = 31
--> Output: 30
x = 4
y = 15.2
--> Output: 12
x = -0.5
y = -10.56
--> Output: -10.5
x = 7
y = 12
--> Output: 7
any idea how can I do it, Sorry guys I’m really a math failer
You would just divide y by x, take the first number without the decimals, and multiply x by that number. I assume you want whole numbers, if so that’s all you need to do.
Yep this should and could be marked as one of the possible the answer (there might be a lot more like @BenMactavsin but I haven’t tested it with all examples). I also came up with the same thing. But here is a list of outputs with the given examples which shows it’s close enough (especially with the -0.5,-10.56 case).
The same function
local function largestMultipleOfNum1(num1,num2)
return math.floor(num2/num1)*num1
end
print(largestMultiple(10,31))
print(largestMultiple(4,15.2))
print(largestMultiple(-0.5,-10.56))
print(largestMultiple(7,12))
You’re not! Nobody was born with the ability to do math, don’t worry about it. If you really want to learn math, you can get there with practice.
Anyway, here’s what I would do:
local function largestMultiple(x, y)
return math.floor(y / x) * x
end
I don’t want to just spoonfeed code, so I’ll explain what this does:
Key knowledge - math.floor
math.floor rounds numbers down. This means math.floor(4.8) will return 4, math.floor(8.3) will return 8, and math.floor(65.9) will return 65.
With that out of the way, let’s break the function down to be even more simple.
local function largestMultiple(x, y)
local div = y / x
local roundedDown = math.floor(div)
return roundedDown * x
end
If you called the function with (10, 31), this would happen:
local function largestMultiple(x, y)
-- x = 10, y = 31
local div = y / x -- This is equal to 3.1 (31 / 10)
local roundedDown = math.floor(div) -- We are rounding it down, so this is now equal to 3
return roundedDown * x -- We're multiplying 3 by x (10), so now we return 30!
end
Because the largest number that is smaller* than -10.56 that can be divided by -0.5 with the remainder of 0 is -10.5, not -10.
*Note: The actual answer is -11 since -11 is smaller than -10.56 but for the purposes of this post made by OP, it’s -10.5.
Another point is is that OP never specified that answer needs to be an integer so there is no reason for the answer to be -10.
@D0RYU@TheHeckingDev Thanks so much for accusing me both of you, but really i dont understand math that much i knew every single math function in roblox but i dont know how to use them to make this function