【華科考研機試題】階乘

題目

輸入n, 求y1=1!+3!+...m!(m是小於等於n的最大奇數) y2=2!+4!+...p!(p是小於等於n的最大偶數)。c++

解題思路

打表算最快,不用每一個數據都算一次。spa

複雜度

時間複雜度(輸入的數據量O(m))
空間複雜度O(1)code

代碼

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;

//實際上算到30的階乘確定溢出了
//可是不要緊,題目給的確定不是溢出的數據 
ll jc[30]; //jc[i]表示i的階乘 
ll ans[30]; // ans[i]表示奇、偶數項階乘和 
int main(){
    //算1~30的階乘 
    jc[0] = 1; 
    for(int i = 1;i < 30; ++i){
        jc[i] = jc[i-1]*i;
    }
    //算奇、偶數項階乘和  
    ans[1] = 1;
    for(int i = 2;i < 30; ++i){
        ans[i] = ans[i-2] + jc[i];
    }
    
    //每一個n直接判斷奇偶輸出便可
    //不用每一個數據再算一次階乘 
    ll n;
    while(cin >> n){
        if(n%2){
            cout << ans[n] << " " << ans[n-1] << endl;
        }else{
            cout << ans[n-1] << " " << ans[n] << endl;
        }
    }
    return 0;
}
相關文章
相關標籤/搜索