Basically, I need to see how many times a number can divide another number before becoming a decimal.
81 can be divided by 3 4 times.
81 / 3 = 27
27 / 3 = 9
9 / 3 = 3
3 / 3 = 1
But how would I put that into code?
Basically, I need to see how many times a number can divide another number before becoming a decimal.
81 can be divided by 3 4 times.
81 / 3 = 27
27 / 3 = 9
9 / 3 = 3
3 / 3 = 1
But how would I put that into code?
Here:
function NumberOfDivides(num1: number, num2: number): number
local result = num1
local count = 0
while result == math.floor(result) do
result = result / num2
count += 1
if result == num1 or result == 1 then
if count == 1 then
result = "-1" -- -1 means infinite
end
break
end
end
return count
end
The function I wrote will give you the number of divisions until it becomes a decimal or reaches 1.
local function NumberOfDivisions(numberToDivide : number, divideBy : number) : number
local numberOfDivisions = 0
while true do
numberToDivide /= divideBy
if numberToDivide % 1 == 0 then
numberOfDivisions += 1
end
if numberToDivide <= 1 then
break
end
end
return numberOfDivisions
end
print(NumberOfDivisions(81, 3)) --> 4
print(NumberOfDivisions(27, 3)) --> 3
print(NumberOfDivisions(1, 10)) --> 0
I know that a solution has already been marked for this post, but I feel like the previous replies complicate matters, when it could be a single line of code:
local function NumberOfDivisions(num1, num2)
return math.floor(math.log(num1, num2))
end
I didn’t even know this was possible. Thank you!
Whoops, I forgot logarithms exist, haha. Great answer! ![]()
This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.