1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

N が M ずつ増えたときにいつ K を越える?

1
Posted at

Paizaで「整数 N, M, K が与えられたとき、N が M ずつ増えて K を越えるのは何回目?」という問題にチャレンジ!一見シンプルだけど、細かい条件でミスった💦


問題概要

  • 整数 N, M, K が与えられる。
  • N が M ずつ増えるとき、何回目に K を越えるか出力する。

入力例:

1 1 10

出力例:

10




❌ NG例

const rl = require('readline').createInterface({input:process.stdin});

rl.once('line', (input) => {
    const [N, M, K] = input.split(' ').map(Number);

    let count = 0;
    for(let temp = N; temp < K; temp += M, count++);
    
    console.log(count);
    
    rl.close();
});

temp < K だと、 temp = K のとき、つまり K を越える前でループが止まってしまう場合がある…。



✅ OK例

const rl = require('readline').createInterface({input:process.stdin});


rl.once('line', (input) => {
    const [N, M, K] = input.split(' ').map(Number);

    let count = 0;
    for(let temp = N; temp <= K; temp += M, count++);
    
    console.log(count);
    
    
    rl.close();
});
  • temp = K のときもループ続行。 
  • 越えるまでループが続き、カウントされる。



📝気づきメモ

  • カウントするときは境界条件の違いに要注意!
  • for文の中に count++ も書くとすっきり書ける!

まとめ

小さな条件でも大きな違い。今回の「<=」の差で痛感した!
そういえば最近、まったく同じような問題を条件分岐メニューの範囲でやった気がする…





僕の失敗談(´;ω;`)と解決法🐈

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?