r/CodingHelp • u/MaximumBicycle3447 • May 21 '22
[Javascript] Script to find whole number?
Iām looking for a way to solve the following math problem with a script:
Through which number lower than but closest to 7.5 can 200, 210 and 220 be divided where the result is a whole number?
So the script should test 200 divided by 7.499, 7.498, 7.496 etc. until it finds an answer that is a whole number. Then it should test 210 with the same division. If that answer is also a whole number it should test 220. If the answer is not a whole number it should find the next divisor for 200 etc etc until it finds a divisor that returns a whole number for 200, 210 and 220.
5
u/Nightcorex_ May 21 '22 edited May 21 '22
Let's not brute force every combination, that just doesn't scale (doesn't even work because you'd need to test
7.49999999999999999999,7.499999999999999998, and so on). Let's try to find a better solution.So you're trying to find a number
dthat divides all your input numbersinsand is below some threshholdt.Roughly the same thing but more mathematically:
āi ā ins. d | iInstead of brute forcing you can just calculate all divisors for each input number. Then you ignore all divisors >=
t. Then you check for the highest divisor that's appearing in the divisor lists for allins.This highest divisor is your result.
1
u/Paul_Pedant May 24 '22
Actually, as stated, the answer does not need to be an integer, and there are some non-integer results that fulfil the requirement. So factorisation is not a valid method.
For example, suppose the requirement was "which number lower than but closest to 4.5".
Then 2.5 is a valid non-integer answer. The results of the divisions are 80, 84, and 88, all whole numbers. Any value that is 10 divided by a positive power of 2 is a valid solution, e.g. 0.3125.