So the goal is to set up prime factorization, i'm using 36 as my default for debugging, except when I run it, it prints out all 3's instead of 2 2 3 3 like it should. In addition it prints out 10 3's instead of just 4, I would think once it exits the while loop, it would stop filling in values? Also that initial include of stdafx.h is a default that isn't helping/hurting so I left it from visual studio express
#include "stdafx.h"
#include <math.h>
#include <iostream>
usingnamespace std;
int main()
{
int x; // user defined number to find prime factorization of
double root; // the sqrt of x, which is mathmatically the
// largest possible factor of a number
// this eliminates excess time trying to generate a solution
int divisor = 2; // used to test % of numbers less than h to see if they
// can evenly divide into x
int i = 0; // array pointer location for outputting prime factors
int primearray[10];
cout << "Welcome to the prime factorization solver!" << endl <<
"Please insert a number to solve for the prime factor: " << endl;
cin >> x;
root = sqrt (x);
while(divisor <= root)
{
if (x%divisor == 0)
{
x = x/divisor;
for (i = 0; i < 10;)
primearray[i++] = divisor;
divisor = 2; // resets to smallest prime number
}
else
{
divisor++;
}
}
cout << "The array is: " << endl;
for(i = 0; i < 10; i++)
cout << primearray[i] << "\t";
system("PAUSE");
return 0;
}
Your code wouldn't even compile for me. according to the information I got on this website the sqrt function does not take an integer argument. http://www.cplusplus.com/reference/cmath/sqrt/
When you use visual studios the #include "stdafx.h" is the precompiled header file. I would recommend creating an empty project, to avoid having that in your program.
I couldn't get your logic to work so I did this instead
#include <math.h>
#include <cstdlib>
#include <iostream>
usingnamespace std;
int main()
{
int primeArray[20];
int count = 0;
int x;
int i = 2;
int j = 0;
cout << "Welcome to the prime factorization solver!" << endl;
cout << "Please insert a number to solve for the prime factor: " << endl;
cin >> x;
if (x < 2)
{
cout << "No prime factors less than 2" << endl;
cin.ignore();
exit(0);
}
while(i <= x)
{
if (x % i == 0)
{
primeArray[count] = i;
x = x / i;
count++;
}
else
{
i++;
}
}/*end of while loop*/
cout << "The array is: " << endl;
for(j = 0; j < count; j++)
cout << primeArray[j] << "\t";
system("PAUSE");
return 0;
}