How would you write a non-recursive algorithm to calculate factorials?

后端 未结 22 968
不思量自难忘°
不思量自难忘° 2020-12-10 11:39

How would you write a non-recursive algorithm to compute n!?

22条回答
  •  轮回少年
    2020-12-10 12:24

    Non recursive factorial in Java. This solution is with custom iterator (to demonstrate iterator use :) ).

    /** 
     * Non recursive factorial. Iterator version,
     */
    package factiterator;
    
    import java.math.BigInteger;
    import java.util.Iterator;
    
    public class FactIterator
    {   
        public static void main(String[] args)
        {
            Iterable fact = new Iterable()
            {
                @Override
                public Iterator iterator()
                {
                    return new Iterator()
                    {
                        BigInteger     i = BigInteger.ONE;
                        BigInteger total = BigInteger.ONE;
    
                        @Override
                        public boolean hasNext()
                        {
                            return true;
                        }
    
                        @Override
                        public BigInteger next()
                        {                        
                            total = total.multiply(i);
                            i = i.add(BigInteger.ONE);
                            return total;
                        }
    
                        @Override
                        public void remove()
                        {
                            throw new UnsupportedOperationException();
                        }
                    };
                }
            };
            int i = 1;
            for (BigInteger f : fact)
            {
                System.out.format("%d! is %s%n", i++, f);
            }
        }
    }
    

提交回复
热议问题