Reputation: 402
I want to write a function to find the next multiple of a number given a multiplier. Both the source number and multiplier could be floating point.
expected:
nextMult(3.654,0.5) = 4.0
nextMult(3.165,0.15) = 3.30
nextMult(3.452,0.002) = 3.452
nextMult(2, 0.3) = 2.1
nextMult(2, 0.2) = 2
nextMult(4, 3) = 6
My current solution:
public double nextMult(double source, double multiplier)
{
for (double i = (double)((long)source - multiplier); i <= source + multiplier;
i += multiplier)
{
if (i >= source)
return i;
}
}
I don't like the multiple castings. Are there more efficient ways or existing library solutions that can do this?
Upvotes: 3
Views: 1284
Reputation: 4024
both source and multiplier are of type: double
double result = Math.ceil(source/multiplier) * multiplier;
This works for all your test cases...
Upvotes: 1
Reputation: 5937
Yes there is. Since you've provided a working solution, you will notice that you've presented an O(n) solution that goes through a set number of operations and appears to increment until you've found it. This becomes terrifying when you do nextMult(10000000000000, 1);
We'd be here all day iterating through that loop by hand.
However, there is actually an O(1) solution.
int multiple = (int) (source / multiplier); //we get the whole number portion of the divided value, i.e. 4/3 = 1, 3.654/0.5 = 7
double remainder = source % multiplier; //we need to check for if it matches the higher
if(remainder > 0) {
multiple++; // and we want the next higher one
}
return multiplier * multiple;
That being said, this only handles POSITIVE values. I will leave handling the negative values up to you as an exercise.
Edit: You will need to implement BigDoubles for modulus. Doubles and modulus apparently hate each other.
Upvotes: 2