Skip to content

The solution done by me in C# on the challenge "Large Factorials" over at www.codewars.com

Notifications You must be signed in to change notification settings

IvanovArtyom/Large-Factorials

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Description:

In mathematics, the factorial of integer n is written as n!. It is equal to the product of n and every integer preceding it.
For example: 5! = 1 x 2 x 3 x 4 x 5 = 120

Your mission is simple: write a function that takes an integer n and returns the value of n!.

You are guaranteed an integer argument. For any values outside the non-negative range, return null, nil or None (return an empty string "" in C and C++). For non-negative numbers a full length number is expected for example, return 25! = "15511210043330985984000000" as a string.

For more on factorials, see http://en.wikipedia.org/wiki/Factorial

NOTES:

  • The use of BigInteger or BigNumber functions has been disabled, this requires a complex solution.
  • I have removed the use of require in the javascript language.

My solution

using System.Collections.Generic;
using System.Linq;

public class Kata
{
    public static string? Factorial(int n)
    {
        if (n < 0)
            return null;

        List<int> factorial = new() { 1 };

        for (int i = 1; i <= n; i++)
            MultiplyLargeNumber(factorial, i);

        return string.Concat(factorial.Select(x => x).Reverse());
    }

    public static void MultiplyLargeNumber(List<int> largeNumber, int number)
    {
        int remainder = 0;

        for (int i = 0; i < largeNumber.Count; i++)
        {
            remainder += largeNumber[i] * number;
            largeNumber[i] = remainder % 10;
            remainder /= 10;
        }

        while (remainder != 0)
        {
            largeNumber.Add(remainder % 10);
            remainder /= 10;
        }
    }
}

About

The solution done by me in C# on the challenge "Large Factorials" over at www.codewars.com

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages