Search code examples
c#declarationfactorial

Factorials and finding the even factorial of them


I'm trying to get my factorial program to work which takes a number from the user and calculates its even factorial. i.e 6! is 720 and its even factorial is 6x4x2 = 48 except I've figured out how to do the factorial part but whenever I try to add more code so I can try calculate the rest I get "Operator % cannot be applied to operands of type method group and int" or "Unexpected symbol { in class, struct, or interface member declaration" and I cant seem to see what I'm doing wrong. Any advice would be helpful

using System;
namespace Factorial
{
    class Factorial
    {
        public static void Main()
        {
            Console.WriteLine("Enter a number");
            int i =int.Parse(Console.ReadLine());
            long fact = GetFactnum(i);
            Console.WriteLine("{0} factorial is {1}", i, fact);           
            Console.ReadKey();
        }

        public static long GetFactnum(int i)
        {          
            if (i == 0)
            {
                return 1;
            }
            return i * GetFactnum(i-1);
        }

     // public static void EvenFact()
     // {
     //     int sumofnums =0;   
     //     if((GetFactnum % 2) ==0)
     //         sumofnums += GetFactnum;
     // }
    }
}

Solution

  • Edit

    You had the basic idea but two things were incorrect.

    First your GetFactnum % 2 part is incorrect syntax. You need to have the form int % int and you basically gave it a method group % int. Which is why you got the error message. So you have to use the result (or return value) of GetFactun(int i) instead of the method name itself, like so:

    int result = GetFactnum(i);
    if((result % 2) == 0)
    

    or you could use the return value immediately:

    if((GetFactnum(i) % 2) == 0)
    

    Secondly, I think you want to first check if the value is even or odd. What happens if you pass in an odd value of i does it still compute the even factorial? Or does it throw an error?

    The way i would code the method is very similar to what you did for GetFactnum(int i). But this time you check the input to see it it is odd or not. And secondly, if it is even, then you know that an even number minus 2 will equal another even number.

    public static long GetEvenFactorial(int i) {
        if((i % 2) != 0) 
        {
            throw new ArgumentException("Input must be even!");
        }
    
        if (i <= 0)
        {
            return 1;
        }
        return i * GetEvenFactorial(i - 2);
    }