I am trying to raise a number to a power using only addition but it does not work, it just raises a number bigger than the original.Here is my code:
private void ExpOperation()
{
result = 0;
num01 = Int32.Parse(inpu01.Text);
num02 = Int32.Parse(inpu02.Text);
int a = num02;
num02 = num01;
int i = 1;
while (i <= a)
{
result = SimpleMulti(num01,num02);
num01 = result;
i++;
}
result_Text.Text = result.ToString();
}
private int SimpleMulti (int num1, int num2)
{
int c = 0;
int i = 1;
while (i <= num2)
{
c += num1;
i++;
}
return c;
}
private int SimpleMulti (int x, int y)
{
int product = 0; //result of multiply
for (int i = 0; i<y; i++){
product += x;
}
//multiplication is repeated addition of x, repeated y times
//the initial solution with a while loop looks correct
return product;
}
private int ExpOperation(int x, int exponent)
{
int result = 1;
if (exponent == 0) {
return result; //anything that powers to 0 is 1
}
else
{
for (int i = 0; i < exponent; i++){
result = SimpleMulti(result, x);
//loop through exponent, multiply result by initial number, x
//e.g. 2^1 = 2, 2^2 = result of 2^1 x 2, 2^3 = result of 2^2 x 2
}
}
return result;
}
Keep in mind that this method does not support negative exponent, which deals with division, but instead of using SimpleMulti, you can create a method for SimpleDivide which uses subtraction instead. The principle is the same
I don't think this question is quite relevant to the main reason of this site, however I got a solution:
public long ExpOperation(int a, int b)
{
long result = 0;
long temp = 0;
for (int i = 1; i <= b; i++) // Executes a full loop when we have successfully multiplied the base number "a" by itself
{
for (int j = 1; j <= a; j++) // Increase the result by itself for a times to multiply the result by itself
result += temp;
temp = result:
}
return result;
}
Because x^y = x * x^(y-1), it can be solved recursively. Since SimpleMulti in question returns integer, I assume both base and exponent are non-negative integer.
private static int PowerWithAddition(int x, int y)
{
if(y == 0){
return 1;
}
var y1 = PowerWithAddition(x, y - 1);
var sum = 0;
for (int i = 0; i < y1; i++)
{
sum += x;
}
return sum;
}
Related
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;
}
Given an array A with zero index and N integers find equal elements with different positions in the array. Pair of indexes (P,Q) such that 0 <= P < Q < N such that A[P] = A[Q]. My algorithm is below but I am looking for a O(N*logN) solution.
public int solution(int[] A)
{
int N = A.Length;
int count = 0;
for (int j = 0; j < N; j++)
{
count += FindPairs(A[j], j, A);
}
return count;
}
public int FindPairs(int item, int ci, int[] A)
{
int len = A.Length;
int counter=0;
int k = ci+1;
while (k < len)
{
if (item == A[k])
counter++;
k++;
}
return counter;
}
From your code, it looks like the goal is to return the count of ascending duplicate pairs in A.
We observe that if there are m occurrences of the number x in A, then the number of ascending duplicate pairs of the value x is m choose 2, or m (m - 1) / 2.
So, we sum up m (m - 1) / 2 for each unique x, giving us the answer.
In pseudocode, this looks like:
count = new Dictionary();
foreach a in A {
count[a]++;
}
total = 0;
foreach key, value in count {
total += value * (value - 1) / 2;
}
return total;
This algorithm is O(N).
Recent interview question … here is what I did:
using System;
using System.Collections.Generic;
using System.Linq;
namespace Codility
{
internal class Program
{
public struct Indice
{
public Indice(int p, int q)
{
P = p;
Q = q;
}
public int P;
public int Q;
public override string ToString()
{
return string.Format("({0}, {1})", P, Q);
}
}
private static void Main(string[] args)
{
// 0 1 2 3 4 5
int[] list = new int[] {3,3,3,3,3,3};
int answer = GetPairCount(list);
Console.WriteLine("answer = " + answer);
Console.ReadLine();
}
private static int GetPairCount(int[] A)
{
if (A.Length < 2) return 0;
Dictionary<int, Dictionary<Indice, Indice>> tracker = new Dictionary<int, Dictionary<Indice, Indice>>();
for (int i = 0; i < A.Length; i++)
{
int val = A[i];
if (!tracker.ContainsKey(val))
{
Dictionary<Indice, Indice> list = new Dictionary<Indice, Indice>();
Indice seed = new Indice(i, -1);
list.Add(seed, seed);
tracker.Add(val, list);
}
else
{
Dictionary<Indice, Indice> list = tracker[val];
foreach (KeyValuePair<Indice,Indice> item in list.ToList())
{
Indice left = new Indice(item.Value.P, i);
Indice right = new Indice(i, item.Value.Q);
if (!list.ContainsKey(left))
{
list.Add(left, left);
Console.WriteLine("left= " + left);
}
if (!list.ContainsKey(right))
{
list.Add(right, right);
Console.WriteLine("\t\tright= " + right);
}
}
}
}
return tracker.SelectMany(kvp => kvp.Value).Count(num => num.Value.Q > num.Value.P);
}
}
}
I think this is best version I got in c#.
static void Main(string[] args)
{
var a = new int[6] { 3, 5, 6, 3, 3, 5 };
//Push the indices into an array:
int[] indices = new int[a.Count()];
for (int p = 0; p < a.Count(); ++p) indices[p] = p;
//Sort the indices according to the value of the corresponding element in a:
Array.Sort(indices, (k, l) =>Compare(a[k], a[l]));
//Then just pull out blocks of indices with equal corresponding elements from indices:
int count = 0;
int i = 0;
while (i < indices.Count())
{
int start = i;
while (i < indices.Count() && a[indices[i]] == a[indices[start]])
{
++i;
}
int thisCount = i - start;
int numPairs = thisCount * (thisCount - 1) / 2;
count += numPairs;
}
Console.WriteLine(count);
Console.ReadKey();
}
//Compare function to return interger
private static int Compare(int v1, int v2)
{
if (v2 > v1)
return 1;
if (v1 == v2)
return 0;
else
return -1;
}
This approach has O(n log n) complexity overall, because of the sorting. The counting of the groups is linear.
Try this:
private static int GetIdenticalPairCount(int[] input)
{
int identicalPairCount = 0;
Dictionary<int, int> identicalCountMap = new Dictionary<int, int>();
foreach (int i in input)
{
if (identicalCountMap.ContainsKey(i))
{
identicalCountMap[i] = identicalCountMap[i] + 1;
if (identicalCountMap[i] > 1)
{
identicalPairCount += identicalCountMap[i];
}
else
{
identicalPairCount++;
}
}
else
{
identicalCountMap.Add(i, 0);
}
}
return identicalPairCount;
}
Test my version:
public int solution(int[] A)
{
int N = A.Length;
int count = 0;
for (int j = 0; j < N - 1; j++)
for (int i = j + 1; i < N; i++)
if (A[i] == A[j])
count++;
return count;
}
I need to find the number of zeroes at the end of a factorial number. So here is my code, but it doesn't quite work :/
using System;
class Sum
{
static void Main(string[] args)
{
int n = int.Parse(Console.ReadLine());
long factoriel = 1;
for (int i = 1; i <= n; i++)
{
factoriel *= i;
}
Console.WriteLine(factoriel);
int timesZero = 0;
while(factoriel % 10 != 0)
{
timesZero++;
}
Console.WriteLine(timesZero);
}
}
I know I can use a for loop and divide by 5, but I don't want to. Where is the problem in my code and why isn't it working?
There's problem with your algorithm: integer overflow. Imagine, that you are given
n = 1000
and so n! = 4.0238...e2567; you should not compute n! but count its terms that are in form of (5**p)*m where p and m are some integers:
5 * m gives you one zero
25 * m gives you two zeros
625 * m gives you three zeros etc
The simplest code (which is slow on big n) is
static void Main(string[] args) {
...
int timesZero = 0;
for (int i = 5; i <= n; i += 5) {
int term = i;
while ((term % 5) == 0) {
timesZero += 1;
term /= 5;
}
}
...
}
Much faster implementation is
static void Main(string[] args) {
...
int timesZero = 0;
for (int power5 = 5; power5 <= n; power5 *= 5)
timesZero += n / power5;
...
}
Counting Trailing zeros in Factorial
static int countZerosInFactOf(int n)##
{
int result = 0;
int start = 1;
while (n >= start)
{
start *= 5;
result += (int)n/start;
}
return result;
}
Make sure to add inbuilt Reference System.Numeric
using System.Text;
using System.Threading.Tasks;
using System.Numeric
namespace TrailingZeroFromFact
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter a no");
int no = int.Parse(Console.ReadLine());
BigInterger fact = 1;
if (no > 0)
{
for (int i = 1; i <= no; i++)
{
fact = fact * i;
}
Console.WriteLine("{0}!={1}", no, fact);
string str = fact.ToString();
string[] ss = str.Split('0');
int count = 0;
for (int i = ss.Length - 1; i >= 0; i--)
{
if (ss[i] == "")
count = count + 1;
else
break;
}
Console.WriteLine("No of trailing zeroes are = {0}", count);
}
else
{
Console.WriteLine("Can't calculate factorial of negative no");
}
Console.ReadKey();
}
}
}
static void Main(string[] args)
{
Console.WriteLine("Enter the number:");
int n = int.Parse(Console.ReadLine());
int zero = 0;
long fac=1;
for (int i = 1; i <= n; i++)
{
fac *= i;
}
Console.WriteLine("Factorial is:" + fac);
ab:
if (fac % 10 == 0)
{
fac = fac / 10;
zero++;
goto ab;
}
else
{
Console.WriteLine("Zeros are:" + zero);
}
Console.ReadLine();
}
Your code seems fine, just a little correction in the while-condition:
public static int CalculateTrailingZeroes(BigInteger bigNum)
{
int zeroesCounter = 0;
while (bigNum % 10 == 0)
{
zeroesCounter++;
bigNum /=10;
}
return zeroesCounter;
}
That works, I just tested it.
"The greatest common divisor of two integers is the largest integer that evenly divides each of the two numbers. Write method Gcd that returns the greatest common divisor of two integers. Incorporate the method into an app that reads two values from the user and displays the result."
(this is not homework, just an exercise in the book I'm using)
can you help me solve this? Here's what I've got so far.
(edit - I can submit the two numbers but it won't calculate the Gcd for me)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Greatest_Common_Divisor
{
class Program
{
static int GetNum(string text)
{
bool IsItANumber = false;
int x = 0;
Console.WriteLine(text);
do
{
IsItANumber = int.TryParse(Console.ReadLine(), out x);
} while (!IsItANumber);
return x;
}
static void Main(string[] args)
{
string text = "enter a number";
int x = GetNum(text);
text = "enter a second number";
int y = GetNum(text);
int z = GCD(x, y);
Console.WriteLine(z);
}
private static int GCD(int x, int y)
{
int v = 0;
int n = 0;
v = GetGreatestDivisor(x, y);
return v;
}
static int GetGreatestDivisor(int m, int h)
{
do
{
for (int i = m; i <= 1; i--)
if (m%i == 0 && h%i == 0)
{
int x = 0;
x = i;
return x;
}
} while (true);
return m;
}
}
}
Here's an implementation of the Euclidean algorithm that returns the greatest common divisor without performing any heap allocation.
You can substitute ulong for uint if needed. An unsigned type is used, as the technique does not work for signed values. If you know your a and b values are not negative, you can use long or int instead.
private static ulong GCD(ulong a, ulong b)
{
while (a != 0 && b != 0)
{
if (a > b)
a %= b;
else
b %= a;
}
return a | b;
}
This method is used in my metadata-extractor library, where it has associated unit tests.
Using LINQ's Aggregate method:
static int GCD(int[] numbers)
{
return numbers.Aggregate(GCD);
}
static int GCD(int a, int b)
{
return b == 0 ? a : GCD(b, a % b);
}
Note: answer above borrowed from accepted answer to Greatest Common Divisor from a set of more than 2 integers.
You can try using this:
static int GreatestCommonDivisor(int[] numbers)
{
return numbers.Aggregate(GCD);
}
static int GreatestCommonDivisor(int x, int y)
{
return y == 0 ? x : GreatestCommonDivisor(y, x % y);
}
Try this:
public static int GCD(int p, int q)
{
if(q == 0)
{
return p;
}
int r = p % q;
return GCD(q, r);
}
public class GCD
{
public int generalizedGCD(int num, int[] arr)
{
int gcd = arr[0];
for (int i = 1; i < num; i++) {
gcd = getGcd(arr[i], gcd);
}
return gcd;
}
public int getGcd(int x, int y)
{
if (x == 0)
return y;
return getGcd(y % x, x);
}
}
Here is a simple solution.
You can use BigInteger to get the greatest common divisor. Just do not forget to add using System.Numerics; to the top of your code.
using System.Numerics;
public class Program{
public static void Main(String[] args){
int n1 = 1;
int n2 = 2;
BigInteger gcd = BigInteger.GreatestCommonDivisor(n1,n2);
Console.WriteLine(gcd);
}
}
Offical Documentation
By using this, you can pass multiple values as well in the form of array:-
// pass all the values in array and call findGCD function
int findGCD(int arr[], int n)
{
int gcd = arr[0];
for (int i = 1; i < n; i++) {
gcd = getGcd(arr[i], gcd);
}
return gcd;
}
// check for gcd
int getGcd(int x, int y)
{
if (x == 0)
return y;
return gcd(y % x, x);
}
List<int> gcd = new List<int>();
int n1, n2;
bool com = false;
Console.WriteLine("Enter first number: ");
n1 = int.Parse(Console.ReadLine());
Console.WriteLine("Enter second number: ");
n2 = int.Parse(Console.ReadLine());
for(int i = 1; i <= n1; i++)
{
if(n1 % i == 0 && n2% i == 0)
{
gcd.Add(i);
}
if(i == n1)
{
com = true;
}
}
if(com == true)
{
Console.WriteLine("GCD of {0} and {1} is {2}.", n1, n2, gcd[gcd.Count - 1]);
}
Console.ReadLine();
If efficiency is not a big concern this will do the job.
// gets greatest common divisor of A and B.
var GCD=Enumerable.Range(1,Math.Min(A,B)).Last(n=>(A%n | B%n)==0);
int[] nums = new int[] {6,12,24,48};
int GCD(int a, int b) => b == 0 ? a : GCD(b, a % b);
int FindGCD(int[] numbers) => numbers.Aggregate(GCD);
Console.WriteLine($"List of numbers ({String.Join(',',nums)})");
Console.WriteLine($"Smallest number: {nums.Min()}");
Console.WriteLine($"Largest number: {nums.Max()}");
Console.WriteLine($"Greatest common devisor of {nums.Min()} and {nums.Max()}: {GCD(nums.Min(),nums.Max())}");
Console.WriteLine($"Aggregate common devisor of array ({String.Join(',',nums)}): {FindGCD(nums)}");
List of numbers (6,12,24,48)
Smallest number: 6
Largest number: 48
Greatest common devisor of 6 and 48: 6
Aggregate common devisor of array (6,12,24,48): 6
using System;
//Write a function that returns the greatest common divisor (GCD) of two integers
namespace GCD_of_Two_Numbers
{
class Program
{
public static void Gcd(int num1, int num2)
{
int[] temp1 = new int[num1];
int[] temp2 = new int[num2];
int[] common = new int[10];
for(int i=2;i<num1/2;i++)
{
if(num1 % i ==0)
{
temp1[i] = i;
}
}
for (int i = 2; i < num2/2; i++)
{
if (num2 % i == 0)
{
temp2[i] = i;
}
}
int len = temp1.Length + temp2.Length;
for(int i=0;i<len;i++)
{
if(temp1[i]==temp2[i])
{
common[i] = temp1[i];
}
}
int max_number = common[0];
for(int i=0;i<common.Length;i++)
{
if(max_number < common[i])
{
max_number = common[i];
}
}
Console.WriteLine($"The Greatest Common Diviser is {max_number}");
}
static void Main(string[] args)
{
Gcd(32, 8);
}
}
}
int a=789456;
int b=97845645;
if(a>b)
{
}
else
{
int temp=0;
temp=a;
a=b;
b=temp;
}
int x=1;
int y=0 ;
for (int i =1 ; i < (b/2)+1 ; i++ )
{
if(a%i==0)
{
x=i;
}
if(b%i==0)
{
y=i;
}
if ((x==y)& x==i & y==i & i < a)
{
Console.WriteLine(i);
}
}
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;
}