【问题标题】:Why can't I prime factor numbers above a certain magnitude?为什么我不能素数超过一定数量级?
【发布时间】:2016-03-04 18:18:40
【问题描述】:

我正在尝试用 C++ 编写一个程序,该程序将质数具有 12 位数字的因子数。这是我的代码:

#include <iostream>
using namespace std;

int main()
{
  long double userInput;
  long double divisor = 2;
  long double dividend;

  cout << "Enter number:   ";
  cin >> userInput;
  dividend = userInput;

  do
  {
    while (static_cast<int>(dividend) % static_cast<int>(divisor) == 0)
    {
      cout << divisor << endl;
      dividend = dividend / divisor;
    }

    divisor++;

  } while (dividend > 1);

  return 0;
}

这(至少似乎)适用于较小的数字,但当我使用非常大的数字时它会崩溃。为什么是这样?我需要使用更大的整数类型吗?还是代码本身有问题?

【问题讨论】:

    标签: c++ int prime-factoring long-double large-data


    【解决方案1】:

    使用long double 进行分解没有多大意义。您需要一个大整数类型来表示整数。 double 通常为 64 位,但它为指数“浪费”了其中的几个位,因此它可以表示小数,也可以表示幅度很大但精度降低的数字。

    此外,您在除以之前将被除数和除数转换为intint 通常是 32 位,这意味着任何超过 20 亿(10 位)的数字都会溢出,从而产生毫无意义的结果。它可以窄至 16 位,这使其范围仅为 -32768 到 +32767;你通常不应该假设它一定比这更宽。

    如果您的编译器支持它(并且可能支持),请使用类型 long long,它至少为 64 位。这接近 19 位十进制数字,足以满足您的要求。

    【讨论】:

    • 此外,int 可以小至 16 位,即 -65,536 到 65,535(二进制补码表示)。
    • @PeteBecker:已更新。 (顺便说一句,它是 -32768 .. +32767。)
    • 我想你不会相信我真的指的是 17 位 int?
    • @PeteBecker:你确定我相信吗?
    • 嗯,有 17 位计算机......academia.edu/7676395/…
    猜你喜欢
    • 2021-03-27
    • 2020-11-01
    • 2011-04-16
    • 1970-01-01
    • 2015-12-02
    • 2011-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多