Nov 23, 2014 at 5:01am Nov 23, 2014 at 5:01am UTC
I've got a very specific homework problem I am working on. I am supposed to find the semi or double factorial of any given positive integer. My program works fine with evens, but not odds. What am I missing?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
int main(){
unsigned long i, num, fact = 1;
cout <<"enter integer: " << endl;
cin >> num;
i = num;
while (num)
{
if (num == 0)
{
fact = 1;
cout << "the double or semifactorial of " << i << " is " << fact << endl;
return 1;
}
if (num == 1)
{
fact = 1;
cout << "the double or semifactorial of " << i << " is " << fact << endl;
return 1;
}
if (num % 2 == 0)
{
fact = fact * num;
num = num - 2;
}
if (num % 2 != 0)
{
fact = (fact * num);
num = (num - 2);
}
}
cout << "the double or semifactorial of " << i << " is " << fact << endl;
}
Last edited on Nov 23, 2014 at 5:05am Nov 23, 2014 at 5:05am UTC
Nov 23, 2014 at 7:17am Nov 23, 2014 at 7:17am UTC
I'd try something like this.
Note: It still breaks on the odd numbers. Working on it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
//doubleFactorial.cpp
//Take integer input and compute the double factorial
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int main(){
unsigned long i, num, fact = 1;
cout <<"enter integer: " << endl;
cin >> num;
i = num;
if (num == 0)
fact = 1;
else if (num == -1)
fact = 1;
else if (num % 2 == 0 && num >= 2)
while (num)
{
fact *= num;
num -= 2;
}
else if (num % 2 !=0 && num >= 1)
while (num >= 1)
{
fact *= num;
num -= 2;
}
cout << "The double or semifactorial of " << i << " is " << fact << endl;
return 0;
}
I sit here, pencil testing it, and I can't find my logic error. This code compiles without a hitch. Throw it an odd number and it just sits there, blinking a cursor at me... and laughing.
Last edited on Nov 23, 2014 at 7:56am Nov 23, 2014 at 7:56am UTC