0
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?

任意の数で何回割れる?

Posted at

今回からしばらく、「ループメニュー」の問題を解いていく!


問題概要

  • 整数 N , M が与えられる。
  • N が何回 M で割れるかを求め、出力する。

入力例:

4 2

出力例:

2



✅OK例:while

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

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

  let count = 0;
  let temp = N;

  while (temp % M === 0) {
    temp /= M;
    count++;
  }

  console.log(count);
  rl.close();
});

✅OK例2:forの条件でまとめて一文に

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


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

    let count = 0;
    for(let result = N;result % M === 0; result /= M, count++);
    
    console.log(count);
    
    
});
  • for文の中で、初期値、条件式、更新式をすべて設定
  • 条件式:resultM で割り切れる間だけ繰り返す
  • 更新式:result /= M(Mで割る)、count++

割り切れる条件(% M === 0)をしっかり書くのがポイント。



📝気づきメモ

  • while文:条件がtrueならどこまでも突き進む無限マシーン。条件式ミスに注意!
  • for文でも初期化・条件・更新をうまくまとめれば同じ動きが可能。可読性は状況により使い分けるのが吉!




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

0
0
1

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
0
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?