天天看點

某校2016專碩程式設計題-求e的值

題目

Java實作

實作1

public static double findE(){
        double e = 1;
        int n = 1; //1,2,3,4,...
        double k = 1; //第n項值
        while (k > 1e-6){
            //計算階乘
            int j = 1;
            for (int i = n; i > 1 ; i--) {
                j *= i;
            }
            k = 1/(double)j;
            e += k;
            n++;
        }
        return e;
    }      
  • 時間複雜度:O(n^2)
  • 空間複雜度:O(1)

實作2

public static double findE2(){

        double e = 0;

        int n = 1; //1,2,3,4,...

        double k = 1; //第n項值

        int a = 1; //分母階乘的值

        while (k > 1e-6){
            e += k;
            a *= n;
            k = 1/(double)a;
            n++;
        }
        return e;
}      
  • 時間複雜度:O(n)
  • 空間複雜度:O(1)

Go實作

func eValue() float64 {
    var n float64 = 1
    var e float64 = 0
    s:= 1
    k := 1
    for n > 1e-6 {
        n = 1/float64(k)
        e += n
        k *= s
        s++
    }
    return e
}      

繼續閱讀