数据结构与算法——计算程序段的执行时间&&多项式求值

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/mozha_666/article/details/79633099

计算程序段的执行时间
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;
}

这里写图片描述

猜你喜欢

转载自blog.csdn.net/mozha_666/article/details/79633099