簡體   English   中英

使用 Lambda 表達式計算階乘

[英]Calculate Factorial using Lambda Expressions

我是 java 的初學者,試圖找出是否有一種方法可以使用 lambda 表達式來計算階乘。 換句話說,我需要做的是修改 fatt 運算符,以便程序輸出階乘數。

import java.util.Stack;

public class TestOperator {


    public static void main(String[] args) {


        Stack<Operator> expression = new Stack<>();

        expression.push(s -> 2);
        expression.push(s -> 3);
        expression.push(s -> 1);
        expression.push(s -> s.pop().apply(s) + s.pop().apply(s));
        expression.push(s -> s.pop().apply(s) * s.pop().apply(s));

        System.out.println(expression.pop().apply(expression)); // prints (1 + 3) * 2 = 8


        // rewrite the operator **Fatt** in order to calculate the factorial


        Operator fatt = (s -> { 

            s.pop().apply(s);

            return 42;

        });

        expression.push(s -> 2);
        expression.push(s -> 3);
        expression.push(s -> 1);
        expression.push(s -> s.pop().apply(s) + s.pop().apply(s));
        expression.push(fatt);
        expression.push(s -> s.pop().apply(s) * s.pop().apply(s));

        System.out.println(expression.pop().apply(expression));
        // it should print fatt(1+3)*2 = 48

    }
}

我想我應該使用 for 循環,但我不知道我應該如何使用 lambda 表達式來應用它。 練習說它也可以使用遞歸來完成。

任何幫助都會有所幫助

謝謝

使用for循環:

public long factorialByForLoop(int value) {
    long result = 1;
    if (value == 0) {
        System.out.print(value);
    } else {
        result = value;
        System.out.print(value);
        for (long i = value - 1; i > 0; i--) {
            System.out.print(" * ");
            result *= i;
            System.out.print(i);
        }
    }
    System.out.print(" = " + result);
    return result;
}

使用recursion算法:

public long factorialByRecursion(int value) {
    long result = value;
    if (value == 1) {
        return value;
    } else {
        return value * factorialByRecursion(--value);
    }
}
import java.math.BigInteger;
import java.util.stream.Stream;

public class FactorialWithLamda {
  public static void main(String[] args){
  BigInteger number = BigInteger.valueOf(21);
  System.out.printf("%d! = %d%n", number, factorial(number));
}
  
public static BigInteger factorial(BigInteger n){
  return Stream.iterate(BigInteger.ONE, i -> 
      i.add(BigInteger.ONE)).
       limit(n.longValue()).
        reduce(BigInteger.ONE, BigInteger::multiply);

}

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM