2019年3月6日水曜日

開発環境

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

コード

#include <iostream>
#include <cmath>

int main()
{
  unsigned long long nums[] = {2, 3, 6, 16, 20, 600851475143};
  size_t len = 6;
  for (size_t i = 0; i < len; i++)
  {
    unsigned long long n = nums[i];
    unsigned long long m = nums[i];
    unsigned long long p = 2;
    while (n % 2 == 0)
    {
      n /= 2;
    }
    int const root = static_cast<int>(std::sqrt(n));
    for (unsigned long long i = 3; i <= root; i += 2)
    {
      if (n % i == 0)
      {
        p = i;
        n /= i;
      }
      while (n % i == 0)
      {
        n /= i;
      }
    }
    if (n > 2)
    {
      p = n;
    }
    std::cout << m << "の最大の素因数は" << p << "。" << std::endl;
  }
}

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

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

sample9_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:sample9_1.exe
sample9_1.obj
2の最大の素因数は2。
3の最大の素因数は3。
6の最大の素因数は3。
16の最大の素因数は2。
20の最大の素因数は5。
600851475143の最大の素因数は6857。

C:\Users\...>

0 コメント:

コメントを投稿