1. 程式人生 > >資料結構與演算法——計算程式段的執行時間&&多項式求值

資料結構與演算法——計算程式段的執行時間&&多項式求值

計算程式段的執行時間
1、計算某一段程式執行的時間,單位秒
2、CLK_TCK:機器每秒的打點數
3、要引入標頭檔案’time.h’

#include<stdio.h>
#include<time.h>
void printNByRecursion(int n){
    if(n){
        printf("%d\n",n);
        printNByRecursion(--n) ;
    }
} 

void printNByLoop(int n){
    for(int i = 1;i<=n;i++){
        printf
("%d\n",i); } return ; } int main(void){ int len = 10000; //clock()函式返回的變數型別 clock_t start,stop; //記錄執行時間,單位秒 double duration; //迴圈 //printNByLoop(len); //遞迴 start = clock(); printNByRecursion(len); stop = clock(); duration = (stop-start)/CLK_TCK; printf
("%f\n",duration); return 0; }

這裡寫圖片描述

多項式求值
1、求多項式的值,以下兩個式子是等價的,這個式子是秦九韶推理公式

Y = a0 *x^0+ a1*x^1+a2*x^2...+an*x^n;
Y = a0+x*(a1+...x(an-2+x*(an-1+x*an)))...);

2、秦九韶公式實現程式碼

#include<stdio.h>
#define LEN 10

void multinomialCount(int n,int a[],int x){
    int i;
    int res = a[LEN-1];
    for
(i = LEN-1;i>0;i--){ res = res*x+a[i-1]; } //return res; printf("%d\n",res); } int main(){ int a[LEN] = {1,2,3,4,5,6,7,8,9,10}; int x = 2; multinomialCount(LEN,a,x); return 0; }

這裡寫圖片描述