## Time complexity analysis for factorial sum

For a rough estimation,

let t = 0! + 1! + 2! + ...,+ (n-1)! + n!, can we assume t = O(n!) ?

let t = n + n(n-1) + n(n-1)(n-2) + ... + n!, can we assume t = O(n*n!) ?

## Given $n$ unique items and an $m^{th}$ normalised value, compute $m^{th}$ permutation without factorial expansion

We know that the number of permutations possible for $$n$$ unique items is $$n!$$. We can uniquely label each permutation with a number from $$0$$ to $$(n!-1)$$.

Suppose if $$n=4$$, the possible permutations with their labels are,

0:  1234 1:  1243 2:  1324 3:  1342 4:  1432 5:  1423 6:  2134 7:  2143 8:  2314 9:  2341 10: 2431 11: 2413 12: 3214 13: 3241 14: 3124 15: 3142 16: 3412 17: 3421 18: 4231 19: 4213 20: 4321 21: 4312 22: 4132 23: 4123 

With any well defined labelling scheme, given a number $$m, 0 \leq m < n!$$, we can get back the permutation sequence. Further, these labels can be normalised to be between $$0$$ and $$1$$. The above labels can be transformed into,

0:       1234 0.0434:  1243 0.0869:  1324 0.1304:  1342 0.1739:  1432 0.2173:  1423 0.2608:  2134 0.3043:  2143 0.3478:  2314 0.3913:  2341 0.4347:  2431 0.4782:  2413 0.5217:  3214 0.5652:  3241 0.6086:  3124 0.6521:  3142 0.6956:  3412 0.7391:  3421 0.7826:  4231 0.8260:  4213 0.8695:  4321 0.9130:  4312 0.9565:  4132 1:       4123 

Now, given $$n$$ and $$m^{th}$$ normalised label, can we get the $$m^{th}$$ permutation while avoiding the expansion of $$n!$$ ? For example, in the above set of permutations, if we were given the $$m^{th}$$ normalised label to be $$0.9$$, is it possible to get the closest sequence 4312 as the answer without computing $$4!$$ ?

## Recurrence relation and time complexity of recursive factorial

I’m trying to find out time complexity of a recursive factorial algorithm which can  be written as:

fact(n) {  if(n == 1)  return 1;  else  return n*fact(n-1)  } 

So I write the recurrence relation as

T(n) = n * T(n-1) 

Which is correct according to this post: Recurrence relation of factorial   And I calculate the time complexity using substitution method as follows:

T(n) = n * T(n-1)  // Original recurrence relation = n * (n-1) * T(n-2) ... = n * (n-1) * ... * 1 = n! 

But according to this post, here, both recurrence relation and time complexity are incorrect.   What am I doing wrong or not getting correctly?

## Como hago para que me de el factorial de numeros mayores a 13?

Todos los resultados menores a 13 me los calcula. Pero cuando pongo 13 me tira un numero random. Estuve averiguando y tiene un integer overflow, mi pregunta ahora es, como hago para evitar que eso pase? Como hago para que me tire los factoriales correctamente. Alguno me podría decir en que parte del código tengo mal las cosas? O como cambiar el integer de 32 bit

.data     msg1: .asciiz "Ingrese un número x:\n"     resultado: .asciiz "Factorial(x) = " .text   main:     # Muestre msg1     li        $v0, 4 la$  a0, msg1     syscall     # Lea x     li        $v0, 5 syscall # Llamada a la función move$  a0, $v0 jal factorial # Salta al factorial y guarda la posicion en$  ra     move      $t0,$  v0        # $t0 =$  v0     # Muestra msg1     li        $v0, 4 la$  a0, resultado     syscall     # print del resultado     li        $v0, 1 # system call #1 - print int move$  a0, $t0 #$  a0 = $t0 syscall # Ejecutar # Devuelve 0 li$  v0, 10        # $v0 = 10 syscall .text factorial: # Ajusta el stack pointer para devolver la direccion guardada y el argumento. addi$  sp, $sp, -8 # Guarda$  s0 en $ra sw$  s0, 4($sp) sw$  ra, 0($sp) bne$  a0, 0, else     addi    $v0,$  zero, 1    # Devuelve 1     j fact_return  else:     # Guarda $a0 move$  s0, $a0 addi$  a0, $a0, -1 # x -= 1 jal factorial # Cuando estamos aca ya tenemos el Factorial(x-1) guardado en$  v0     multu   $s0,$  v0 # Devuelve x*Factorial(x-1)     mflo    $v0 fact_return: lw$  s0, 4($sp) lw$  ra, 0($sp) addi$  sp, $sp, 8 jr$  ra 

## Descomposición de factorial javascript

Estoy resolviendo un problema que consiste en descomponer el factorial de un numero en sus primos…

function decomp(n) {     let multiplicadores = ''     let factorial = 1;     for (let i = 2; i <= n; i++) {         factorial *= i     }     const numero = factorial     for (let j = 2; j <= factorial; j++) {         let contador = 0         while (factorial % j == 0) {             factorial /= j             contador++         }         if (contador == 1) multiplicadores += ${j} *  if (contador > 1) multiplicadores += $  {j}^${contador} *  } return Resultado de descomponer$  {n}! = ${numero}:$  {multiplicadores.substr(0, multiplicadores.length - 3)} } console.log(decomp(5)); console.log(decomp(12)); console.log(decomp(25));

el problema esta en que cuando lo hago con numeros muy grandes ej: 25! me regresa 2^31 * 17^2 * 969743 * 25772783 cuando el resultado deberia ser 2^22 * 3^10 * 5^6 * 7^3 * 11^2 * 13 * 17 * 19 * 23… Ahora no se con que tamanno de numeros trabaja javascript pero cuando hago los calculos para este numero que me da como resutado el 25!: 1.5511210043330986e+25 ambas soluciones estan bien cosa que no deberia pasar pq estoy simplificando por numeros primos.. cuando simplifico 1.5511210043330986e+25/Math.pow(2,22) = 3698160658676859400 numero q se puede continuar simplificando por 2…

## Recursive Function for factorial

Sorry as this is a basic one….. This code isn’t working for large numbers,it shows error

# include

long long int fact(long long int n){ if(n<=1){ return n; } else{ return(n*fact(n-1)); } } int main(){ long long int num,x; std::cin>>num; x=fact(num); std::cout<

}

I’ve been experiencing this performance issue for about 3 days and really need your help. I’m a novice at c# and cannot understand what I can do to optimize my application.

The problem is that the UI is not as responsive as it must be while many items are loading.

I decided to write an application on learning purpose where we can calculate factorial of the input big number. It’s also important to make calculations concurrently in several threads.

I also want to bind a progress bar to the progress of calculations and show interim calculations.

For example: Input number: 5

Interim calculations:

0!=1 1!=1 2!=2 3!=6 4!=24 5!=120 

Result: 5!=120

Everything is fine when the input number is less then 1000. If it’s more then freezes are coming.

What I’ve tried:

1. At first I’ve tried to write my own observable concurrent collection where I add my items from other threads.
2. Then I’ve tried to push interim results, which are calculated by other threads, into ConcurrentQueue from which I will dequeue them into my observable collection.
3. I’ve tried to turn on virtualization but it also didn’t help. Actually, I’m pretty sure that the problem is in my collection that ItemSource is binded to is growing and when I add more elements to this collection then it starts redrawing completly.

CalculationProcessView:

<UserControl x:Class="FactorialCalculator.WPF.Views.CalculationProcessView"          xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"          xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"          xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"           xmlns:d="http://schemas.microsoft.com/expression/blend/2008"           xmlns:local="clr-namespace:FactorialCalculator.WPF.Views"          mc:Ignorable="d"           d:DesignHeight="450" d:DesignWidth="800">  <StackPanel>     <Label Content="Calculation:"/>      <Border BorderBrush="Gainsboro" BorderThickness="0,2">         <ListBox              x:Name="CalculationProcessListBox"             Height="100"             ItemsSource="{Binding Path=Calculations, Mode=OneWay, IsAsync=True}"             VirtualizingPanel.IsContainerVirtualizable="True"             VirtualizingPanel.IsVirtualizing="True"             VirtualizingPanel.VirtualizationMode="Recycling"             VirtualizingPanel.CacheLengthUnit="Page"             VirtualizingPanel.CacheLength="2,2">              <ListBox.Template>                 <ControlTemplate>                     <ScrollViewer>                         <ItemsPresenter />                     </ScrollViewer>                 </ControlTemplate>             </ListBox.Template>              <ListBox.ItemsPanel>                 <ItemsPanelTemplate>                     <VirtualizingStackPanel />                 </ItemsPanelTemplate>             </ListBox.ItemsPanel>          </ListBox>     </Border>      <ProgressBar Minimum="0"                  Maximum="{Binding ProgressBarMaxValue}"                  Value="{Binding Calculations.Count, Mode=OneWay}"                  Height="28" /> </StackPanel> 

CalculatorFormViewModel:

namespace FactorialCalculator.WPF.ViewModels {     public class CalculatorFormViewModel : BaseViewModel, ICalculatorFormViewModel     {         private string _progressBarMaxValue;         private ICommand _calculateCommand;         private IModelFactory _modelFactory;         private SystemTimer _dispatcherTimer;         private ICalculationModel _calculation;         private ICommandFactory<RelayCommand> _commandFactory;         private IFactorialCalculationService _factorialCalculationService;         private static object _syncLock = new object();          public CalculatorFormViewModel(Dispatcher uiDispatcher,                                        IModelFactory modelFactory,                                        ICommandFactory<RelayCommand> commandFactory,                                        IFactorialCalculationService factorialCalculationService) : base(uiDispatcher)         {             _modelFactory = modelFactory;             _commandFactory = commandFactory;             _factorialCalculationService = factorialCalculationService;             _calculation = _modelFactory.CreateCalculationModel();             Calculations = new ConcurrentSortedList<ICalculationModel>();             BindingOperations.EnableCollectionSynchronization(Calculations, _syncLock);         }          public ConcurrentSortedList<ICalculationModel> Calculations { get; set; }          public string ProgressBarMaxValue         {             get { return _progressBarMaxValue; }             set             {                 _progressBarMaxValue = value;                 NotifyPropertyChanged("ProgressBarMaxValue");             }         }          public ICalculationModel Calculation         {             get             {                 return _calculation;             }             set             {                 _calculation = value;                 NotifyPropertyChanged("Calculation");             }         }          #region ICalculatorFormViewModel implementation          public ICommand CalculateCommand         {             get             {                 return _calculateCommand ??                   (                       _calculateCommand                             = _commandFactory.CreateCommand(                                  _ => this.Calculate().FireAndForgetSafeAsync(null))                   );             }         }          public async Task Calculate()         {             if (_factorialCalculationService.IsInPorcess)             {                 _factorialCalculationService.StopCalculation();             }              if (BigInteger.TryParse(Calculation.InputNumber, out BigInteger number))             {                 try                 {                     Calculations.Clear();                      ProgressBarMaxValue = Calculation.InputNumber;                     StartMonitoringCalculationProgress();                      await _factorialCalculationService.StartCalculation(number);                 }                 finally                 {                     StopMonitoringCalculationProgress();                 }             }             else             {                 throw new ArgumentException("Incorrect input value!");             }         }          #endregion          protected void StartMonitoringCalculationProgress()         {             _dispatcherTimer = new SystemTimer() { Interval = 500 };              _dispatcherTimer.Elapsed += (o, args) =>             {                  if (_factorialCalculationService                             .TryGetInterimResults(out IDictionary<BigInteger, BigInteger> interimResults))                 {                     lock (_syncLock)                     {                         Calculations.AddItems(                             interimResults.Select(                                     (item) =>                                     {                                         var calculationModel = _modelFactory.CreateCalculationModel();                                          calculationModel.InputNumber = item.Key.ToString();                                         calculationModel.Factorial = item.Value.ToString();                                          return calculationModel;                                     }                                 ).ToList()                         );                     }                 }             };              _dispatcherTimer.Start();         }          protected void StopMonitoringCalculationProgress()         {             _dispatcherTimer.Stop();             _dispatcherTimer.Dispose();         }     } } 

FactorialCalculationService:

namespace FactorialCalculator.Application.Services {     public class FactorialCalculationService : IFactorialCalculationService     {         private bool _isCanceled;         private bool _isInPorcess;         private CancellationTokenSource _tokenSourse;         private ConcurrentQueue<IDictionary<BigInteger, BigInteger>> _calculationQueue;         private readonly IFactorialCalculatorService _factorialCalculatorService;          public FactorialCalculationService(IFactorialCalculatorService factorialCalculatorService)         {             _isCanceled = false;             _isInPorcess = false;             _factorialCalculatorService = factorialCalculatorService;             _calculationQueue = new ConcurrentQueue<IDictionary<BigInteger, BigInteger>>();         }          #region IFactorialCalculationService implementation          public bool IsInPorcess => _isInPorcess;          public bool TryGetInterimResults(out IDictionary<BigInteger, BigInteger> interimResults)         {             return _calculationQueue.TryDequeue(out interimResults);         }          public Task StartCalculation(BigInteger number)         {             return                  Task.Run(                     () =>                     {                         try                         {                             _isCanceled = false;                             _isInPorcess = true;                             _tokenSourse = new CancellationTokenSource();                              _factorialCalculatorService.Calculate(                                                              number,                                                              (dictionary) => _calculationQueue.Enqueue(dictionary),                                                              _tokenSourse.Token                                                          );                               //Wait while all the results will be consumed                             while (!_calculationQueue.IsEmpty);                         }                         catch (AggregateException ax)                         {                             ax.Handle(ex => {                                 OperationCanceledException exception = ex as OperationCanceledException;                                  if (exception != null)                                 {                                     _isCanceled = true;                                 }                                  return exception != null;                             });                          }                         finally                         {                             _isInPorcess = false;                         }                     }                 );         }          public void StopCalculation()         {             if (!_isCanceled)             {                 _calculationQueue = new ConcurrentQueue<IDictionary<BigInteger, BigInteger>>();                 _tokenSourse.Cancel();             }         }          #endregion     } } 

FactorialCalculatorService:

namespace FactorialCalculator.Domain.Services {     public class FactorialCalculatorService : IFactorialCalculatorService     {         private int _maxTasks;          #region IFactorialCalculatorService implementation          public BigInteger Calculate(BigInteger number,                                     Action<IDictionary<BigInteger, BigInteger>> callback = null,                                     CancellationToken cancellationToken = default(CancellationToken))         {             if (number < 0)                 throw new ArgumentOutOfRangeException(nameof(number));              BigInteger countOfTasks = number / Environment.ProcessorCount;             countOfTasks = countOfTasks > int.MaxValue ? int.MaxValue : (int)countOfTasks;             _maxTasks = countOfTasks == 0 ? 1 : (int)countOfTasks;              var tasks = ParallelizeCalculation(number, callback, cancellationToken);              Task.WaitAll(tasks);              return GetFinalResult(tasks);         }          #endregion           protected virtual BigInteger CalculateClass(BigInteger upperBound,                                                     BigInteger startFrom,                                                     CancellationToken cancellationToken = default(CancellationToken),                                                     Action<IDictionary<BigInteger, BigInteger>> callback = null)         {             cancellationToken.ThrowIfCancellationRequested();              SortedDictionary<BigInteger, BigInteger> calculationHistory = new SortedDictionary<BigInteger, BigInteger>();              for (var i = startFrom; i <= upperBound; i += _maxTasks)             {                 //Thread.Sleep(50);                 cancellationToken.ThrowIfCancellationRequested();                  var internalResult = Calculate(i);                 calculationHistory.Add(i, internalResult);             }              callback?.Invoke(calculationHistory);              return calculationHistory.Last().Value;         }          protected virtual BigInteger Calculate(BigInteger number)         {             BigInteger result = 1;              for (BigInteger i = result; i <= number; i++)             {                 result *= i;             }              return result;         }          protected virtual Task<BigInteger>[] ParallelizeCalculation(BigInteger number,                                                         Action<IDictionary<BigInteger, BigInteger>> callback = null,                                                         CancellationToken cancellationToken = default(CancellationToken))         {             var tasks = Enumerable.Range(0, _maxTasks)                                   .Select(                                             i => Task.Factory.StartNew(                                                 () => CalculateClass(number, i, cancellationToken, callback),                                                 TaskCreationOptions.AttachedToParent                                             )                                          )                                   .ToArray();               return tasks;         }          private BigInteger GetFinalResult(Task<BigInteger>[] tasks)         {             BigInteger finalResult = 1;              foreach(var task in tasks)             {                 finalResult *= task.Result;             }              return finalResult;         }     } } 

ConcurrentSortedList:

namespace FactorialCalculator.WPF.Infrastructure.Collections {     public class ConcurrentSortedList<T> : ObservableCollection<T>     {         private readonly ReaderWriterLockSlim _lock;         private bool suspendCollectionChangeNotification;          public ConcurrentSortedList()             : base()         {             this.suspendCollectionChangeNotification = false;             _lock = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);         }          public override event NotifyCollectionChangedEventHandler CollectionChanged;           public void AddItems(IList<T> items)         {             try             {                 _lock.EnterWriteLock();                  this.SuspendCollectionChangeNotification();                  foreach (var i in items)                 {                     Add(i);                 }             }             finally             {                 _lock.ExitWriteLock();             }              this.NotifyChanges();           }         public new void Add(T item)         {             try             {                 _lock.EnterWriteLock();                  int i = 0;                 while (i < Items.Count && Comparer<T>.Default.Compare(Items[i], item) < 0)                     i++;                  Items.Insert(i, item);             }             finally             {                 _lock.ExitWriteLock();             }              OnPropertyChanged(new System.ComponentModel.PropertyChangedEventArgs("Count"));         }           public void NotifyChanges()         {             this.ResumeCollectionChangeNotification();             var arg = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset);             this.OnCollectionChanged(arg);         }          public void RemoveItems(IList<T> items)         {             try             {                 _lock.EnterWriteLock();                  this.SuspendCollectionChangeNotification();                  foreach (var i in items)                 {                     Remove(i);                 }             }             finally             {                 _lock.ExitWriteLock();             }              this.NotifyChanges();         }          public void ResumeCollectionChangeNotification()         {             this.suspendCollectionChangeNotification = false;         }          public void SuspendCollectionChangeNotification()         {             this.suspendCollectionChangeNotification = true;         }          protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)         {              using (BlockReentrancy())             {                 if (!this.suspendCollectionChangeNotification)                 {                     NotifyCollectionChangedEventHandler eventHandler =                           this.CollectionChanged;                     if (eventHandler == null)                     {                         return;                     }                      Delegate[] delegates = eventHandler.GetInvocationList();                      foreach (NotifyCollectionChangedEventHandler handler in delegates)                     {                         DispatcherObject dispatcherObject                              = handler.Target as DispatcherObject;                          if (dispatcherObject != null                                && !dispatcherObject.CheckAccess())                         {                             dispatcherObject.Dispatcher.BeginInvoke(DispatcherPriority.DataBind, handler, this, e);                         }                         else                         {                             handler(this, e);                         }                     }                 }             }         }       } } 

BaseViewModel

public abstract class BaseViewModel : INotifyPropertyChanged {     protected readonly Dispatcher _uiDispatcher;      protected BaseViewModel(Dispatcher uiDispatcher)     {         _uiDispatcher = uiDispatcher;     }      #region INotifyPropertyChanged implementation      public event PropertyChangedEventHandler PropertyChanged;      protected void NotifyPropertyChanged([CallerMemberName] string propertyName = null)     {         var propertyChanged = PropertyChanged;         if (propertyChanged == null)         {             return;         }          _uiDispatcher.Invoke(() => propertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName)));     }      #endregion } 

App:

Source code: enter link description here

## Calculating the Factorial of a Number and getting the final number in a message box

I am stuck on a problem from my Visual C# text book. The question is as follows; (omitting the part about how factorials work)

Create an application that lets the user enter a nonnegative integer and then uses a loop to calculate the factorial of that number. Display the factorial in a label or a message box.

So basically to start I would have a textbook where the user enters a number, then pressed a button to trigger the event handler which will start the loop.

I’ll be honest, I am totally new to C# and am completely stumped on this one. I am not sure if I should be using a while or for loop for this. At the end of the it should displayed with the final product.

## Solving recurrence relation with minimum and factorial

I need to solve the following recurrece:

$$T(n,m)=\begin{cases} 1, & m\leq 2(n-1)!\ \min\limits_{a,b,c\geq 1\a\leq c!\b\leq(n-c)!\c\leq n-1}{T(c,a)+T(n-c,b)+T(n,m-ab)}, & \text{else} \end{cases}$$

Note: This question is highly related to my previous question here, since $$ab\leq\max\limits_{1\leq c\leq n-1}{c!(n-c)!}=(n-1)!$$

I guess that the closed form expression for $$T(n,m)$$ here is similar to the one that has been found for my previous question.

Also, I guess that the minimum is obtained at $$c=\lceil n/2\rceil,a=c!,b=(n-c)!$$, but I don’t know how to prove it.

Any help would be highly appreciated!

## Why iterative code times out for calculating the number of trailing zeros in A factorial

Both the codes caluclate the trailing number of zeros in A!.

Here is the iterative code : It times out for large input

public int trailingZeroes(int A) {   int count=0;   for(int i=5;A/5>=1;i=i*5)  {     count+=A/i;  }   return count; } 

And here is the recursive code and it gets completed in time.

public int trailingZeroes(int A) {  return A==0?0:(A/5 + trailingZeroes(A/5)); } 

Does in all cases, recursive codes are faster than iterative codes ? e.g. Tree Traversals etc.