The first version I made just outputted the list of factors, but then I wanted something that I could just #include to any project and get a list of factors (relatively) quickly. This is the result as of this writing.
(main doesn't do much except ask if the utility should loop or just quit after the first list of factors; everything that could be reused is here)
I managed to narrow the segfault down to near the end of the 12th run of the last for loop. If anyone could help with this, it would be much appreciated.
vector <vector <long> > factor (long num, vector <vector <long> > factors, int argc, char * const argv [] ) {
#pragma mark variable declarations
long factorsLength = 0 ;
long min ;
long max ;
bool breakOnCheck = false ;
bool skipStandardAddition ; // Resets at the start of each loop
bool dontAddToFactorsList ; // Resets at the start of each loop
if (num > 0) {
min = num * -1 ;
max = num ;
}
if (num < 0) {
min = num ;
max = num * -1 ;
}
#pragma mark test factor
for (long i = min ; i <= max ; i ++ ) {
if (i == 0) i ++ ;
if (num % i == 0) factorsLength ++ ;
}
#pragma mark set up vector sizes
factors.resize (factorsLength) ;
for (int i = 0 ; i < factorsLength ; i ++ ) factors [i] .resize (2) ;
#pragma mark factor
for (long i = min ; i <= max ; i ++ ) {
#pragma mark -beginning resets
skipStandardAddition = false ;
dontAddToFactorsList = false ;
if (i == 0) i ++ ;
#pragma mark -if i is a factor (if num / i has a remainder of 0)
if (num % i == 0) {
#pragma mark --make sure the factor pair is not already in the list
for (long j = 0 ; j <= factors.size () ; j ++ ) {
if (i == factors [j] [0] || num / i == factors [j] [0] || i == factors [j] [1] || num / i == factors [j] [1] ) {
dontAddToFactorsList = true ;
if (breakOnCheck == true) break ;
else breakOnCheck = true ;
}
#pragma mark --if the factors are the same (if i equals num / i) add one copy to the first column; add 0 to the second
if (i == num / i) {
if (breakOnCheck == true) break ;
else {
breakOnCheck = true ;
skipStandardAddition = true ;
}
}
#pragma mark --if there aren't any skip flags (if skipStandardAddition and dontAddToFactorsList are false) , add the factors to the list
if (skipStandardAddition == false && dontAddToFactorsList == false) {
factors.resize (factors.size () + 1) ;
factors [factors.size () ] .resize (2) ;
factors [factors.size () ] [0] = i ;
factors [factors.size () ] [1] = num / i ;
}
}
}
}
return factors ;
}
Loop? (y|n) : n
Please enter an integer: 12
Segmentation fault
logout
[Process completed]
Note: I edited out all of the code and output that just says where in the code the utility is.