【TopCoder】SRM163 DIV2 Lv.1
問題文概略
シャクトリムシが休憩しながら枝を進んでいく。休憩した地点に葉っぱがあるときに葉っぱを食べるのだが、枝を渡り切るまでに何枚の葉を食べられるか求めよ。
書いたコード
public class Inchworm { public int lunchtime(int branch, int rest, int leaf) { int x = branch / rest; int y = branch / leaf; int ansA = 0, ansB = 0, count = 0; for(int i = 0; i <= x; i++) { ansA = rest * i; for(int j = 0; j <= y; j++) { ansB = leaf * j; if(ansA == ansB) { count++; } } } return count; } }
他の参加者のコードを読んで修正した
public class Inchworm { public int lunchtime(int branch, int rest, int leaf) { int cur = 0; int ans = 0; while(cur <= branch) { if(cur % leaf == 0) ans++; cur += rest; } return ans; } }
雑感
はじめは「restとleafの最小公倍数を求めるにはどうすればよいか?」と考えていたのだが、片方に×1,×2,…としていき、もう片方で割り切れるかを判断すればよかった。 片方を×1,×2,…としていく部分も、単純にその数字を足していけばよかった。