ありがとう。これまでのところ、私は私の元の解決策だけで運があったが、私はまだ何か良いものを見たいと思う。ここで私がしようとアイデアを促進支援するために構築され、簡単なテストクラスである:(問題のある)
package com.scratch;
import java.util.ArrayList;
import java.util.List;
public class Test {
private static class Values {
long x;
long y;
long result;
Values(long x, long y, long result) {
this.x = x;
this.y = y;
this.result = result;
}
}
/**
* @param args
*/
public static void main(String[] args) {
List<Values> list = new ArrayList<Values>();
Values v1 = new Values(18, 3, 18);
list.add(v1);
Values v2 = new Values(18, 5, 20);
list.add(v2);
Values v3 = new Values(121, 25, 125);
list.add(v3);
Values v4 = new Values(9999999, 10, 10000000);
list.add(v4);
Operation operation = new MyFormula();
// Operation operation = new RecommendedFormula();
// Operation operation = new RecommendedFormula2();
for (Values v : list) {
System.out.println(v.x + ", " + v.y + " => " + v.result + "?");
long res = operation.perform(v.x, v.y);
System.out.println(res == v.result ? "worked" : "nope... Expected "
+ v.result + ", got " + res);
}
}
private static interface Operation {
long perform(long x, long y);
}
private static class MyFormula implements Operation {
@Override
public long perform(long x, long y) {
return x - ((x % y) == 0 ? y : x % y) + y;
}
}
private static class RecommendedFormula implements Operation {
@Override
public long perform(long x, long y) {
return (long) (Math.ceil(x/y) * y);
}
}
private static class RecommendedFormula2 implements Operation{
@Override
public long perform(long x, long y) {
return x + (y - x % y) % y;
}
}
}
MyFormulaだけで正常に動作するようです。推奨された形式はありませんが、それは私が使用したタイプ(最終製品で使用する必要があるタイプ)のためだけである可能性があります。
私は実際にあなたのソリューションが好きです。 –
私は直感的にあなたの解決策を考え出しました。他のスマートなトリックがあるかもしれませんが、もっと効率的なものが見つかるはずです。 –
これをmath.stackexchange.com –