-1

I'm trying to write a program in C++ that will prime factor numbers that have 12 digits. Here's my code:

#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;
}

This (seems to, at least) works fine for smaller numbers, but it breaks down when I use really high numbers. Why is this? Do I need to use a larger integer type? Or is it something wrong with the code itself?

Community
  • 1
  • 1
David Bippes
  • 65
  • 2
  • 4

1 Answers1

3

Using long double for factorization doesn't make much sense. You want a large integer type to represent whole numbers. double is typically 64 bits, but it "wastes" several of those bits for the exponent so it can represent fractional numbers, and also numbers with a very large magnitude but reduced precision.

Also, you convert the dividend and divisor to int before dividing them. int is very often 32 bits, which means any number over about 2 billion (10 digits) will overflow, giving meaningless results. It can be as narrow as 16 bits, which gives it a range of just -32768 to +32767; you usually shouldn't assume that it's necessarily wider than that.

If your compiler supports it (and it probably does), use type long long, which is at least 64 bits. That's nearly 19 decimal digits, which is more than enough for your requirements.

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631