Home > front end >  Fastest way to determine how many times a number can be sutracted in a total number, while each subt
Fastest way to determine how many times a number can be sutracted in a total number, while each subt

Time:11-25

Is it possible to solve the following problem without a cycle? By using a math formula. It could make my app much faster.

How many times can 43920 be subtracted in 189503, while each subtraction result is greater than 79920

Example:

189503 > 79920 so 189503-43920=145583 (1 time)
145583 > 79920 so 145583-43920=101663 (2 times)
101663 > 79920 so 101663-43920=57743 (3 times)
57743 < 43920 so it means it ran 3 times
This would be the same as 189503-(43920*3) = 57743 or 189503 % (43920*3)

I don't know if i wrote my question well, maybe you can help

CodePudding user response:

Yes. It resumes to: Math.floor((189503 - 79920) / 43920). Which equals 2.

  1. First subtract 79920 to keep only the distance that you really care.
  2. Divide the remainder by 43920. This will result in the "exact" number of times it can be subtracted.
  3. Finally, apply a floor function to get an integer number.

CodePudding user response:

Let x = the number of times you need to subtract by

189503 - (43920 * x) = 79920

189503 = 79920   (43920 * x)

189503 - 79920 = 43920x

x = (189503 - 79920) / 43920

x = 2.49505919854

Given that you can not really subtract something any other than a whole number (integer) of times the answer is 2.

  • Related