I wrote a short program to factor numbers, and it works in most cases. The problem I am getting is that when I use a very large number I get "Floating point exception: 8." I am assuming that I am trying to divide by 0 on line 43 or 46, but I cannot quite figure out when/why it would do this. primes.txt is a file with the prime numbers between 2-1,000,000 with one number to a line.
primes.txt: https://www.dropbox.com/sh/e3u6prd0pqrhet0/4M4yXYyJIF/primes.txt

//  main.cpp
//  Factor
//  Created by Samuel Witt on 11/8/12.
//  Copyright (c) 2012 Samuel Witt. All rights reserved.

#include <iostream>
#include <cstdlib>
#include <fstream>
#include <vector>
#include <cmath>
using namespace std;

int main(int argc, const char * argv[])
    //initialize variables
    int composite = atoi(argv[argc-1]), num;
    long int numPrimes;
    vector <int> primes;
    ifstream in("primes.txt");

    //retrieve prime numbers less than the composite
        in >> num;

    }while ((!in.eof()) && (composite > num));

    numPrimes = primes.size();

    vector <int> factors;

    //read largest number less than "composite" and see if it divides without a remainder. if it does, it is pushed into the "factors" vector and composite=composite/potentialFactor
            //if the value in the back of "primes" divides into composite evenly
        if(composite%primes.back() == 0)
                //composite becomes the solution of itself divided by the prime number
            composite = (composite/primes.back());
                //the prime number is added to the vector of factors
                //the prime number is deleted from the list

    } while ((primes.size() > 0) && (composite >= 2));

    //print out the list of prime factors
    if (factors.size() > 0)
        while (factors.size() > 0)
            cout << factors.back();
            if (factors.size() != 0)
                cout << ", ";
    cout << endl;
        cout << composite << " is prime!" << endl;

    return 0;

Edited 4 Years Ago by Sam_07: Typos, added primes.txt link

Note with the given word bank, numbers whose factorazation includes a prime greater than 1,000,000 (such as 5,744,074,063) will be incorrectly factored, but the program still thinks that it has factored correctly.

You are using a long int which has a max value of 2,147,483,647 so if you give it 5,744,074,063 it is going to wrap around. you can try using a long long which is 64 bits with a max value of 9,223,372,036,854,775,807

Awesome, Thanks!
Out of curiosity, could I initialize something like "long long long long int num;" ?

The bigest you can get with and int is a long long. You can get a large number library that has no restrictions except for the amount of ram you have in your system. GMP should be able to help you out if you need anything larger than 9,223,372,036,854,775,807 as an int type

Edited 4 Years Ago by NathanOliver

This article has been dead for over six months. Start a new discussion instead.