2019年3月5日火曜日

開発環境

Modern C++チャレンジ ―C++17プログラミング力を鍛える100問 (Marius Bancila(著)、島 敏博(監修)、黒川 利明(翻訳)、オライリージャパン)の1章(数学の問題)、問題8(アームストロング数)の解答の練習問題の解答を求めてみる。

コード

#include <iostream>
#include <cmath>

size_t number_of_digits(size_t n)
{
  auto t = 0;

  do
  {
    t++;
    n /= 10;
  } while (n != 0);

  return t;
}

int main()
{
  int limit = 0;
  std::cout << "上限: ";
  std::cin >> limit;
  auto count = 0;
  for (auto i = 1; i <= limit; i++)
  {
    auto k = number_of_digits(i);
    auto j = i;
    auto t = 0;
    while (j != 0)
    {
      t += std::pow(j % 10, k);
      if (t > i)
      {
        continue;
      }
      j /= 10;
    }
    if (i == t)
    {
      count++;
      std::cout << count << "個目: " << i << std::endl;
    }
  }
}

入出力結果(VS 2017 用 x64 Native Tools コマンド プロンプト、Terminal)

C:\Users\...>cl /O2 sample8_1.cpp && sample8_1.exe
Microsoft(R) C/C++ Optimizing Compiler Version 19.16.27027.1 for x64
Copyright (C) Microsoft Corporation.  All rights reserved.

sample8_1.cpp
C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.16.27023\include\xlocale(319): warning C4530: C++ 例外処理を使っていますが、アンワインド セマンティクスは有効にはなりません。/EHsc を指定してください。
Microsoft (R) Incremental Linker Version 14.16.27027.1
Copyright (C) Microsoft Corporation.  All rights reserved.

/out:sample8_1.exe
sample8_1.obj
上限: 9999
1個目: 1
2個目: 2
3個目: 3
4個目: 4
5個目: 5
6個目: 6
7個目: 7
8個目: 8
9個目: 9
10個目: 153
11個目: 370
12個目: 371
13個目: 407
14個目: 1634
15個目: 8208
16個目: 9474

C:\Users\...>

0 コメント:

コメントを投稿