Click to See Complete Forum and Search --> : simple factoring doesn't work


Arez
June 11th, 2008, 06:52 PM
hey what's wrong with this i can't find it


#include <iostream>
using namespace std;

int main()
{
int a,b,c;
cout << "Enter a number ";
cin >> a;
for (int n=1; n<a; n++)
{
b=a*(a-n);
c=c+b;
}
cout << c;
return 0;
}


its supposed to factor but doesn't!

TheCPUWizard
June 11th, 2008, 07:26 PM
What happens when you step through the debugger?

Write down the values of a,b,c, and n during each post. You will soon see the problem. If you don't then post the list of numbers and we can go through it....

Arez
June 12th, 2008, 12:47 AM
Yeah, I am really lost here...

when I entered in 9, it gave the number 2293722, 1 gives 2293672...


b=a*(a-n);
c=c+b;


if I entered in 5, it should have made it do this


5*(5-1)
5*(5-2)
5*(5-3)
5*(5-4)

Alan-LB
June 12th, 2008, 01:22 AM
You need to clear c first. Add a statement
c = 0;
after
cin >> a;

Alan.

Arez
June 12th, 2008, 04:25 PM
You need to clear c first. Add a statement
c = 0;
after
cin >> a;

Alan.

I did that, and it didn't work (when I entered in 9 it gave 324 instead of 362880) :(

It did make the behavior a little better though

Lindley
June 12th, 2008, 05:45 PM
Oh, you're trying to calculate a factorial? That's rather different than factoring. I was wondering how the heck that code was supposed to work.....

Assuming overflow isn't a concern, calculating a factorial is a lot easier than you seem to be making it out to be.