数据结构初识—— f(x)多项式的算法优化

来源:互联网 发布:葛优 知乎 编辑:程序博客网 时间:2024/06/05 16:40

//在一个给定的x求值double f(int n,double a[],double x){    int i;    double p = a[0];//擦,这个算法也很牛逼了    //就是按照题目的意思,把多项式依次相加。    for (i = 1;i <= n;i ++)        p += (a[i] * pow(x,i));    return p;}double f(int n,double a[],double x) {    int i;    double p = a[n];    //这个就牛逼大发了,从a[n]开始由内而外    for (i = n;i > 0;i --)        p = a[i-1] + x*p;    return p;}

#include <stdio.h>#include <time.h>clock_t start,stop;//clock_t是clock()函数返回的变量类型double duration;//记录被测函数运行的时间,以秒为单位int main(){   //不在测试范围内的准备工作写在clock()之前    start = clock();    MyFunction();    stop = clock();    duration = ((double)(stop - start))/CLK_TCK;    //计算运行时间    //其他不在测试范围的处理写在后面,例如输出duration的值    return 0;}

经过放大以后的运算效率对比。

非常重要的一点,如果函数太快,会显示不了时间。所以要增加循环次数,累加时间

阅读全文
0 0