I would like to rewrite the functionality of this algorithm (which I used to solve ProjectEuler problem 15) in a non recursive way.
Yes, I realise there are many better ways to solve the actual problem, but as a challenge I would like to simplify this logic as much as possible.
public class SolveRecursion
{
public long Combination = 0;
public int GridSize;
public void CalculateCombination(int x = 0, int y = 0)
{
if (x < GridSize)
{
CalculateCombination(x + 1, y);
}
if (y < GridSize)
{
CalculateCombination(x, y + 1);
}
if (x == GridSize && y == GridSize)
Combination++;
}
}
And tests:
[Test]
public void SolveRecursion_GivenThree_GivesAnswerOf20Routes()
{
solveRecursion.GridSize = 3;
solveRecursion.CalculateCombination();
var result = solveRecursion.Combination;
Assert.AreEqual(20, result);
}
[Test]
public void SolveRecursion_GivenFour_GivesAnswerOf70Routes()
{
solveRecursion.GridSize = 4;
solveRecursion.CalculateCombination();
var result = solveRecursion.Combination;
Assert.AreEqual(70, result);
}
EDIT: Here is another simple function written in both ways:
//recursion
private int Factorial(int number)
{
if (number == 0)
return 1;
int returnedValue = Factorial(number - 1);
int result = number*returnedValue;
return result;
}
//loop
private int FactorialAsLoop(int number)
{
//4*3*2*1
for (int i = number-1; i >= 1; i--)
{
number = number*i;
}
return number;
}
Any hints would be greatly appreciated. I've tried dynamic programming solution (which uses a more maths based approach), and an equation to successfully solve the puzzle.
I wonder - can this first algorithm be made non recursive, simply?
The non-recursive solution is:
const int n = 4;
int a[n + 2][n + 2] = {0};
a[0][0] = 1;
for (int i = 0; i < n + 1; ++i)
for (int j = 0; j < n + 1; ++j) {
a[i][j + 1] += a[i][j];
a[i + 1][j] += a[i][j];
}
std::cout << a[n][n] << std::endl;
Just for information, this problem should have been solved on the paper, the answer for NxM grid is C(N+M,N), where C is the combination function - http://en.wikipedia.org/wiki/Combination
Related
Find the sum of all prime numbers not greater than N. For example if user input 5 then prime numbers are 2,3,5 and their sum is 10. It is not passing 4 test cases in which two of them are exceeding the time limit. I have tried several test cases and my code is working fine on them. Here is my code.
public static long sieve_of_eratosthenes(long n)
{
if (n == 1)
{
// If the user input 1.
return (0);
}
else
{
long sum = 0;
bool[] array = new bool[n + 1];
for (long i = 2; i <= n; i++)
{
// Setting all values to true.
array[i] = true;
}
// Eliminating the composite numbers.
for (long j = 2; j < Math.Sqrt(n); j++)
{
if (array[j])
{
long multiple = 1;
for (long k = (j * j); k <= n; k = (j * j) + (j * (multiple++)))
{
array[k] = false;
}
}
}
//Now we have the prime numbers. We just have to add them.
for (int z = 2; z <= n; z++)
{
if (array[z])
{
sum = sum + z;
}
}
return (sum);
}
}
static void Main(string[] args)
{
int noofcases = int.Parse(Console.ReadLine());
for( int i = 0; i < noofcases; i ++)
{
long entry = long.Parse(Console.ReadLine());
Console.WriteLine(sieve_of_eratosthenes(entry));
}
}
check the below code. I wrote simple logic which you can improve
public static class Int32Extension
{
public static bool IsPrime(this int number)
{
if (number <= 1) return false;
if (number == 2) return true;
if (number % 2 == 0) return false;
var boundary = (int)Math.Floor(Math.Sqrt(number));
for (int i = 3; i <= boundary; i += 2)
if (number % i == 0)
return false;
return true;
}
}
then
static void Main(string[] args)
{
int input = 5;
int sum = 0;
for (int i = 0; i < input;)
{
if (!(++i).IsPrime())
continue;
sum += i;
}
Console.WriteLine(sum);
}
Without using Extension Method
public static bool IsPrime(int number)
{
if (number <= 1) return false;
if (number == 2) return true;
if (number % 2 == 0) return false;
var boundary = (int)Math.Floor(Math.Sqrt(number));
for (int i = 3; i <= boundary; i += 2)
if (number % i == 0)
return false;
return true;
}
static void Main(string[] args)
{
int input = 5;
int sum = 0;
for (int i = 0; i < input;)
{
if (!IsPrime(++i))
continue;
sum += i;
}
Console.WriteLine(sum);
}
.Net Fiddle Link : https://dotnetfiddle.net/rEBY9r
Edit : The IsPrime test uses Primality Test With Pseudocode
The numbers are stored in the arrays with their digits in reverse order. Here is a functions that should multiply two numbers, lhs and rhs, and store the product in result:
public static void MultiplyDigitArrays(int[] lhs, int[] rhs, int[] result)
{
int length1 = Math.Max(lhs.Length, rhs.Length);
for (int i = 0; i < length1; i++)
{
int[] PartialProduct = new int[result.Length];
int length2 = Math.Min(lhs.Length, rhs.Length);
for (int j = 0; j < length2; j++)
{
int multiplicand = (lhs.Length < rhs.Length) ? rhs[i] : lhs[i];
int multiplier = (lhs.Length < rhs.Length) ? lhs[j] : rhs[j];
int product = PartialProduct[i + j] + multiplicand * multiplier;
PartialProduct[i + j] = product % 10;
int carry = product / 10;
PartialProduct[i + j + 1] = PartialProduct[i + j + 1] + carry;
}
SumDigitArrays(PartialProduct, result, result);
}
}
However, if I multiply:
static void Main(string[] args)
{
int[] n1 = { 1, 1 };
int[] n2 = { 1, 1 };
int[] result = new int[Math.Max(n1.Length, n2.Length) * 2 + 1];
MultiplyDigitArrays(n1, n2, result);
PrintArray(result);
Console.WriteLine();
}
the result is:
00132
instead of the expected:
00121
What am I doing wrong?
For the MCVE:
public static void PrintArray(int[] Array)
{
int length = Array.Length;
for (int i = length - 1; i >= 0; i--)
{
Console.Write(Array[i]);
}
}
public static void SumDigitArrays(int[] a, int[] b, int[] result)
{
int length = Math.Max(a.Length, b.Length);
for (int i = 0; i < length; i++)
{
int lhs = (i < a.Length) ? a[i] : 0;
int rhs = (i < b.Length) ? b[i] : 0;
int sum = result[i] + lhs + rhs;
result[i] = sum % 10;
int carry = sum / 10;
if (i + 1 < result.Length)
{
result[i + 1] = result[i + 1] + carry;
}
}
}
The reason is because the third parameter use you in calling SumDigitArrays should be empty. Instead, you feed it the result variable which contains data on any iteration other than the first.
Implement your method like this:
public static int[] MultiplyDigitArrays(int[] lhs, int[] rhs)
{
int length1 = Math.Max(lhs.Length, rhs.Length);
var result = new int[length1* length1];
for (int i = 0; i < length1; i++)
{
int[] PartialProduct = new int[length1 * length1];
int length2 = Math.Min(lhs.Length, rhs.Length);
for (int j = 0; j < length2; j++)
{
int multiplicand = (lhs.Length < rhs.Length) ? rhs[i] : lhs[i];
int multiplier = (lhs.Length < rhs.Length) ? lhs[j] : rhs[j];
int product = PartialProduct[i + j] + multiplicand * multiplier;
PartialProduct[i + j] = product % 10;
int carry = product / 10;
PartialProduct[i + j + 1] = PartialProduct[i + j + 1] + carry;
}
result = SumDigitArrays(PartialProduct, result);
}
return result;
}
public static int[] SumDigitArrays(int[] a, int[] b)
{
int length = Math.Max(a.Length, b.Length);
var result = new int[length];
for (int i = 0; i < length; i++)
{
int lhs = (i < a.Length) ? a[i] : 0;
int rhs = (i < b.Length) ? b[i] : 0;
int sum = result[i] + lhs + rhs;
result[i] = sum % 10;
int carry = sum / 10;
if (i + 1 < result.Length)
{
result[i + 1] = result[i + 1] + carry;
}
}
return result;
}
I don't exactly understand the logic you are performing, but
int product = PartialProduct[i + j] + multiplicand * multiplier;
Gets evaluated as
int product = PartialProduct[i + j] + (multiplicand * multiplier);
Did you intend it to do
int product = (PartialProduct[i + j] + multiplicand) * multiplier;
As that could explain your error.
Apart from the two other answers given (which are spot-on and solve your problem), unless you have a very specific need, I'd recommend going for BigInteger if you need to multiply very large numbers.
For your specific needs (in case your numbers must come and go in an array of ints, which is a weird way to store any number), your Multiply could become:
public static void MultiplyDigitArrays(int[] lhs, int[] rhs, int[] result)
{
var n1 = BigInteger.Parse(string.Join("", lhs));
var n2 = BigInteger.Parse(string.Join("", rhs));
var resultBi = BigInteger.Multiply(n1, n2);
Array.Clear(result, 0, result.Length);
var stResult = resultBi.ToString().PadLeft(result.Length, '0');
for(int i = 0; i < stResult.Length; i++)
{
result[(stResult.Length-1)-i] = int.Parse(stResult[i].ToString());
}
}
Note that the burden of this function is actually converting your integer array back and forth, since an integer array is a weird format to store a number.
If you work directly with strings (or BigIntegers), this function would just not be necessary. For example, if working with strings containing the numbers, this could become:
public static string MultiplyBigNumbers(string lhs, string rhs)
{
var n1 = BigInteger.Parse(lhs);
var n2 = BigInteger.Parse(rhs);
return BigInteger.Multiply(n1, n2).ToString();
}
And just call it: MultiplyBigNumbers("3242", "42349");
Then again, I'd recommend just working with BigInteger all the way down, and have it converted whenever you need to store it (for which a byte array makes more sense, and you can get it with ToByteArray()) or display (which can be easily done with a ToString() call)
Note that passing an array for the result is also pretty weird (for .NET anyway), since you don't need the original values. You'd be better off returning an array and calculating the needed length in the function itself, not having the caller figure it out.
I am solving this problem, in which they ask for the index of the first Fibonacci number of 1000 digits, and my first idea was something similar to:
BigInteger x = 1;
BigInteger y = 1;
BigInteger tmp = 0;
int currentIndex = 2;
while (x.NoOfDigits < 1000)
{
tmp = x + y;
y = x;
x = tmp;
currentIndex++;
}
return currentIndex;
However, as far as I can tell, there is no method for counting the number of digits of a BigInteger. Is this true? One way of circumventing it is to use the .ToString().Length method of a BigInteger, but I'm told that string processing is slow.
A BigInteger also has a .ToByteArray(), and I thought of converting a BigInteger to a byte array and checking the length of that array - but I don't think that this uniquely determines the number of digits in the BigInteger.
For what it's worth, I implemented another way of solving it, which is manually storing the Fibonacci numbers in array, and which stops as soon as the array is full, and I compared this to the .ToString-based method, which is about 2.5 times slower, but the first method takes 0.1 second, which also seems like a long time.
Edit: I've tested the two suggestions in the answers below (the one with BigInteger.Log and the one with MaxLimitMethod). I get the following run times:
Original method: 00:00:00.0961957
StringMethod: 00:00:00.1535350
BigIntegerLogMethod: 00:00:00.0387479
MaxLimitMethod: 00:00:00.0019509
Program
using System;
using System.Collections.Generic;
using System.Numerics;
using System.Diagnostics;
class Program
{
static void Main(string[] args)
{
Stopwatch clock = new Stopwatch();
clock.Start();
int index1 = Algorithms.IndexOfNDigits(1000);
clock.Stop();
var elapsedTime1 = clock.Elapsed;
Console.WriteLine(index1);
Console.WriteLine("Original method: {0}",elapsedTime1);
Console.ReadKey();
clock.Reset();
clock.Start();
int index2 = Algorithms.StringMethod(1000);
clock.Stop();
var elapsedTime2 = clock.Elapsed;
Console.WriteLine(index2);
Console.WriteLine("StringMethod: {0}", elapsedTime2);
Console.ReadKey();
clock.Reset();
clock.Start();
int index3 = Algorithms.BigIntegerLogMethod(1000);
clock.Stop();
var elapsedTime3 = clock.Elapsed;
Console.WriteLine(index3);
Console.WriteLine("BigIntegerLogMethod: {0}", elapsedTime3);
Console.ReadKey();
clock.Reset();
clock.Start();
int index4 = Algorithms.MaxLimitMethod(1000);
clock.Stop();
var elapsedTime4 = clock.Elapsed;
Console.WriteLine(index4);
Console.WriteLine("MaxLimitMethod: {0}", elapsedTime4);
Console.ReadKey();
}
}
static class Algorithms
{
//Find the index of the first Fibonacci number of n digits
public static int IndexOfNDigits(int n)
{
if (n == 1) return 1;
int[] firstNumber = new int[n];
int[] secondNumber = new int[n];
firstNumber[0] = 1;
secondNumber[0] = 1;
int currentIndex = 2;
while (firstNumber[n-1] == 0)
{
int carry = 0, singleSum = 0;
int[] tmp = new int[n]; //Placeholder for the sum
for (int i = 0; i<n; i++)
{
singleSum = firstNumber[i] + secondNumber[i];
if (singleSum >= 10) carry = 1;
else carry = 0;
tmp[i] += singleSum % 10;
if (tmp[i] >= 10)
{
tmp[i] = 0;
carry = 1;
}
int countCarries = 0;
while (carry == 1)
{
countCarries++;
if (tmp[i + countCarries] == 9)
{
tmp[i + countCarries] = 0;
tmp[i + countCarries + 1] += 1;
carry = 1;
}
else
{
tmp[i + countCarries] += 1;
carry = 0;
}
}
}
for (int i = 0; i < n; i++ )
{
secondNumber[i] = firstNumber[i];
firstNumber[i] = tmp[i];
}
currentIndex++;
}
return currentIndex;
}
public static int StringMethod(int n)
{
BigInteger x = 1;
BigInteger y = 1;
BigInteger tmp = 0;
int currentIndex = 2;
while (x.ToString().Length < n)
{
tmp = x + y;
y = x;
x = tmp;
currentIndex++;
}
return currentIndex;
}
public static int BigIntegerLogMethod(int n)
{
BigInteger x = 1;
BigInteger y = 1;
BigInteger tmp = 0;
int currentIndex = 2;
while (Math.Floor(BigInteger.Log10(x) + 1) < n)
{
tmp = x + y;
y = x;
x = tmp;
currentIndex++;
}
return currentIndex;
}
public static int MaxLimitMethod(int n)
{
BigInteger maxLimit = BigInteger.Pow(10, n - 1);
BigInteger x = 1;
BigInteger y = 1;
BigInteger tmp = 0;
int currentIndex = 2;
while (x.CompareTo(maxLimit) < 0)
{
tmp = x + y;
y = x;
x = tmp;
currentIndex++;
}
return currentIndex;
}
}
Provided that x > 0
int digits = (int)Math.Floor(BigInteger.Log10(x) + 1);
will get the number of digits.
Out of curiosity, I tested the
int digits = x.ToString().Length;
approach. For 100 000 000 iterations, it's 3 times slower than the Log10 solution.
Expanding on my comment--instead of testing based on number of digits, test based on exceeding a constant that has the upper limit of the problem:
public static int MaxLimitMethod(int n)
{
BigInteger maxLimit = BigInteger.Pow(10, n);
BigInteger x = 1;
BigInteger y = 1;
BigInteger tmp = 0;
int currentIndex = 2;
while (x.CompareTo(maxLimit) < 0)
{
tmp = x + y;
y = x;
x = tmp;
currentIndex++;
}
return currentIndex;
}
This should result in a significant performance increase.
UPDATE:
This is an even quicker method on .NET 5 (since GetBitLength() is required):
private static readonly double exponentConvert = Math.Log10(2);
private static readonly BigInteger _ten = 10;
public static int CountDigits(BigInteger value)
{
if (value.IsZero)
return 1;
value = BigInteger.Abs(value);
if (value.IsOne)
return 1;
long numBits = value.GetBitLength();
int base10Digits = (int)(numBits * exponentConvert).Dump();
var reference = BigInteger.Pow(_ten, base10Digits);
if (value >= reference)
base10Digits++;
return base10Digits;
}
The slowest part of this algorithm for large values is the BigInteger.Pow() operation. I have optimized the CountDigits() method in Singulink.Numerics.BigIntegerExtensions with a cache that holds powers of 10, so check that out if you are interested in the fastest possible implementation. It caches powers up to exponents of 1023 by default but if you want to trade memory usage for faster performance on even larger values you can increase the max cached exponent by calling BigIntegerPowCache.GetCache(10, maxSize) where maxSize = maxExponent + 1.
On an i7-3770 CPU, this library takes 350ms to get the digit count for 10 million BigInteger values (single-threaded) when the digit count <= the max cached exponent.
ORIGINAL ANSWER:
The accepted answer is unreliable, as indicated in the comments. This method works for all numbers:
private static int CountDigits(BigInteger value)
{
if (value.IsZero)
return 1;
value = BigInteger.Abs(value);
if (value.IsOne)
return 1;
int exp = (int)Math.Ceiling(BigInteger.Log10(value));
var test = BigInteger.Pow(10, exp);
return value >= test ? exp + 1 : exp;
}
I am a beginner in C# and I wanted to implement the following Pseudo code of the FFT algorithm:
function fft(n, f):
if (n = 1)
return f
else
g = fft(n/2, (f_0, f_2, ..., f_{n-2}))
u = fft(n/2, (f_1, f_3, ..., f_{n-1}))
for k = 0 to n/2 - 1
c_k = g_k + u_k*exp(-2*pi*i*k/n)
c_{k+n/2} = g_k-u_k*exp(-2*pi*i*k/n)
return c
I tried to implement that in C# as you can see:
public static class FFT
{
public static Complex[] fft(Complex[] f)
{
if (f.Length == 1)
{
return f;
}
else
{
Complex[] g = fft(even_indices(f));
Complex[] u = fft(odd_indices(f));
Complex[] c = new Complex[f.Length];
for (int k = 0; k < f.Length / 2 - 1; k++)
{
Complex w_k = u[k] * Complex.FromPolarCoordinates(1.0, -2 * Math.PI * k / f.Length);
c[k] = g[k] + w_k;
c[k + f.Length / 2] = g[k] - w_k;
}
return c;
}
}
private static Complex[] even_indices(Complex[] f)
{
Complex[] f_even = new Complex[f.Length / 2];
for (int i = 0; i < f.Length; i++)
{
if (i % 2 == 0)
{
f_even[i / 2] = f[i];
}
}
return f_even;
}
private static Complex[] odd_indices(Complex[] f)
{
Complex[] f_odd = new Complex[f.Length / 2];
for (int i = 0; i < f.Length; i++)
{
if (i % 2 == 1)
{
f_odd[(i-1)/2] = f[i];
}
}
return f_odd;
}
}
class Program
{
static void Main()
{
Complex[] test = { 1.0, 2.454167, 8.4567, 9.4564 };
var data = FFT.fft(test);
Console.WriteLine("FFT");
for (int i = 0; i < data.Length; i++)
{
Console.WriteLine(data[i]);
}
Console.ReadKey();
}
}
Now there is no error message and it gets completely compiled. However, the output is
FFT
(0, 0)
(0, 0)
(0, 0)
(0, 0)
which is not what I want. What is wrong here?
Thanks again
Complex[] c = new Complex[f.Length / 2 - 1];
I would round up, so + 1..
f.Length == 2 would return 0 for array length.
I'd expect the error actually resulting from the next line:
c[k + f.Length / 2] = g[k] - u[k] * Complex.Exp(-w_k);
where you add len/2 to the k-index - which will eventually result in a index > length/2-1. (dev of 'c').
If the rest is correct you should declare c as:
Complex[] c = new Complex[f.Length];
Add:
in your code, the loop should iterate uo to len/2-1, so change to:
for (int k = 0; k <= f.Length / 2 - 1; k++)
Currently I have this set of code and its meant to calculate factorials.
int numberInt = int.Parse(factorialNumberTextBox.Text);
for (int i = 1; i < numberInt; i++)
{
numberInt = numberInt * i;
}
factorialAnswerTextBox.Text = numberInt.ToString();
For some reason it doesn't work and i have no clue why. For example i will input 3 and get the answer as -458131456 which seems really strange.
Any help appreciated. Thanks
int numberInt = int.Parse(factorialNumberTextBox.Text);
int result = numberInt;
for (int i = 1; i < numberInt; i++)
{
result = result * i;
}
factorialAnswerTextBox.Text = result.ToString();
on a side note: this would normally NOT be the correct way to calculate factorials.
You'll need a check on the input before you can begin calculation, in case your starting value is 1 or below, in that case you need to manually return 1.
On another side note: this is also a perfect example of where recursive methods can be useful.
int Factorial(int i)
{
if (i <= 1)
return 1;
return i * Factorial(i - 1);
}
A little late to the party:
Func<int, int> factorial = n => n == 0 ? 1 :
Enumerable.Range(1, n).Aggregate((acc, x) => acc * x);
You can use this (rather elegant) solution:
Func<int, int> factorial = null;
factorial = x => x <= 1 ? 1 : x * factorial(x-1);
int numberInt = int.Parse(factorialNumberTextBox.Text);
factorialAnswerTextBox.Text = factorial(numberInt).ToString();
public static int Factorial(int facno)
{
int temno = 1;
for (int i = 1; i <= facno; i++)
{
temno = temno * i;
}
return temno;
}
i am late to the party but here it is
public ulong Factorial(uint numb)
{
if (numb <= 1) return 1;
ulong final = 1;
for (uint i = 1; i <= numb; i++)
{
final *= i;
}
return final;
}
Note:
i used un-signed types for better range
as this calculates up to Factorial(65), while normal signed types will give negative values
Trying to make a more bulletproof solution for n factorial. Here is one that guards for overflows, as well as negative and zero values of n. Using a result variable of type long (instead of int) allows for "larger" values to be calculated (for long, you can calculate up to and including n = 20).
This code returns 0 if an overflow occurred, but you can change it to do whatever is more appropriate.
static long nFactorial(int n)
{
if (n <= 1)
{
return 1;
}
long result = 1;
try
{
for (int i = 1; i <= n; i++)
{
result = checked(result * i);
}
}
catch (OverflowException)
{
return 0;
}
return result;
}
I had to create a factorial method for calculating combinations and tripped over the fact that factorials get very big very fast with relatively small inputs. Here's my solution without using recursion to avoid stack overflow and implemented using System.Numerics.BigInteger.
static BigInteger factorial(int num) {
BigInteger result = 1;
while (num > 1) {
result *= num--;
}
return result;
}
Obviously, you could also using BigInteger for input but my use case was that I was processing int values.
use factorial function:
static long Factorial(long number)
{
if( number <= 1 )
return 1;
else
return number * Factorial(number - 1);
}
and then call the function:
long result = Factorial(int.Parse(factorialNumberTextBox.Text));
factorialAnswerTextBox.Text = result.ToString();
int numberInt=1 ;
for (int i = 1; i <= int.Parse(factorialNumberTextBox.Text); i++)
{
numberInt = numberInt * i;
}
factorialNumberTextBox.Text = numberInt.ToString();
Try this,
int numberInt = int.Parse(textBox1.Text);
int answer = 1;
for (int i = 1; i <= numberInt; i++)
{
answer = answer * i;
}
textBox1.Text = answer.ToString();
Two methods are implemented: Recursive and Basic factorial calculation.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication50
{
class Program
{
static void Main(string[] args)
{
NumberManipulator manipulator = new NumberManipulator();
Console.WriteLine("Please Enter Factorial Number:");
int a= Convert.ToInt32(Console.ReadLine());
Console.WriteLine("---Basic Calling--");
Console.WriteLine("Factorial of {0} is: {1}" ,a, manipulator.factorial(a));
Console.WriteLine("--Recursively Calling--");
Console.WriteLine("Factorial of {0} is: {1}", a, manipulator.recursively(a));
Console.ReadLine();
}
}
class NumberManipulator
{
public int factorial(int num)
{
int result=1;
int b = 1;
do
{
result = result * b;
Console.WriteLine(result);
b++;
} while (num >= b);
return result;
}
public int recursively(int num)
{
if (num <= 1)
{
return 1;
}
else
{
return recursively(num - 1) * num;
}
}
}
}
static void Main()
{
int numberFactorial = int.Parse(Console.ReadLine());
int result = numberFactorial;
for (int i = 1; i < numberFactorial; i++)
{
result = result * i;
Console.WriteLine("{0}*{1}",numberFactorial,i);
}
Console.WriteLine(result);
}
A nice factorial solution for your nice evening.
int num = Convert.ToInt32(Console.ReadLine());
int fact = 1;
for (int i = num; i > 0; --i)
fact *= i;
Console.WriteLine(fact);
public static void Main(string[] args)
{
string result = Convert.ToString(GetFactorial(5));
Console.WriteLine(result);
}
internal static int GetFactorial(int factNumber)
{
int factorial =1;
int i = factNumber;
while(factNumber>=1)
{
factorial = factNumber * factorial;
factNumber--;
}
return factorial;
}
How about this?
public int FactorialFunction(int Factorial){
int Product = Factorial -1;
for(int Number = Factorial - 1; Number < Factorial; Number++ ) {
Factorial = Product * Factorial;
Product--;
}
return Factorial;
}