So the biggest issue is that there is a missing brace at the end of your factors function. you need to add another brace after the if (n > 1) brace. Also, there is a missing semicolon at the end of the last cout that will throw an error.
Another issue that won’t prevent the code from running is that when you print “The result: ” << x you will be giving the same value as the user input.
If you want your main function to print out the result from factors() at that spot, then the function needs to return the data instead of printing it. To fix this, the factors function can be made to return a string with the output you want:
//return a string with the output
string factors(int n){
//create a string to save the output to
string factorlist = "";
int z = 2;
while (z * z <= n)
{
if (n % z == 0)
{
//append z to the end of the string and add a space to make it easier to read
factorlist+=to_string(z)+" ";
n = (n / z);
}
else
{
z++;
}
}
if (n > 1)
{
//append n to the end of the string and add a newline
factorlist+=to_string(n)+"\n";
}
//output the string factorlist to wherever the function was called from
return factorlist;
}
then on the lines that look like:
factors(x);
cout << "The result: " << x
Should be:
cout << "The result: " << factors(x);
Currently, you are just printing out the value of x that the user input. If you want to save the value of factors(x) you would need to set a variable equal to it like this:
string FactorsResult = factors(x)
And then print it; or, as in the corrected code above, just print it directly in the cout statement.
9
solved C++ Compute prime factors of a number and print them