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
do
{
in >> num;
primes.push_back(num);
}while ((!in.eof()) && (composite > num));
in.close();
primes.pop_back();
numPrimes = primes.size();
//=========================BEGIN=FACTORING=HERE===================================================
vector <int> factors;
do
{
//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
factors.push_back(primes.back());
}
else
//the prime number is deleted from the list
primes.pop_back();
} while ((primes.size() > 0) && (composite >= 2));
//print out the list of prime factors
if (factors.size() > 0)
{
while (factors.size() > 0)
{
cout << factors.back();
factors.pop_back();
if (factors.size() != 0)
cout << ", ";
}
cout << endl;
}
else
cout << composite << " is prime!" << endl;
//DONE!
return 0;
}