This is an online interview problem and I came up with the solution below. The interviewer came back and said my solution was not compiling and I was not selected :( Can someone tell me what could be wrong in my solution? Is it with the IDE? I used Visual Studio Express 2013. I am not good at figuring out how to code it to make it compatible for all compilers and IDE, can someone take a look at this and let me know what might be the best way to fix it?
Problem Statement:
Write a program in C++ that takes a positive integer and prints out all ways to multiply smaller integers that equal the original number, without repeating sets of factors. In other words, if your output contains 4 * 3, you should not print out 3 * 4 again as that would be a repeating set. Note that this is not asking for prime factorization only.
#include "iostream"
#include "math.h"
#include "string"
#include "sstream"
usingnamespace std;
/**
* @Method printFactors: Method to print factors for an input number
* @Input Parameters:
* prevString - previous multiplication string passed to the function
* preDiv - previous divisor value to be used in printFactors method
* num - number to be factorized
*/
void printFactors(string prevString, int prevDiv, int num){
if (num < 2) return;//return to calling function if number is less than 2
stringstream ss;
int maxDivisor = (int)ceil(sqrt((double)num)); //calculate max divisor number to find the factors
for (int i = 2; i <= maxDivisor; i++){
if (num%i == 0){ //Check to see if i is a factor of number
int quo = num / i; //find quotient of a number
if (i >= prevDiv && quo >= i){ //Check to avoid printing repeated factors
cout << prevString << i << "*" << quo << endl;
ss.clear();
ss << prevString << i << "*"; //Build string for finding factors
printFactors(ss.str(), i, quo); //recursive call to print factors for the quotient
}
}
}
}
int main(){
int num;
cout << "Enter the number to print factors: ";
cin >> num;
cin.clear();
cin.ignore(INT_MAX, '\n');
cout << "1*" << num << endl; //printing the first factor of number * 1
printFactors("", 1,num);
getchar();
return 0;
}