多项式计算-C语言递归实现

开始输入多项式X的值和幂数,跟着输入每项的系数,算法通过递归实现X的n次方,最后返回多项式的值。这种算法的好处是,所需的计算步骤只有传统各项乘法的一半,利用了X^n=X^(n/2)*X^(n/2)的捷径,所以不用每次都去乘以本身。

#include <stdio.h>
#include <stdlib.h>
long summation(int x,int n);
int main()
{
    int x,n,c=0;
    long sum=0;
    printf("Enter x and n:");
    scanf("%d %d",&x,&n);
    while(n>=0)
    {
        if(n>0)
        {
            printf("Enter the power %d 's co-efficiency:",n);
        }
        else
        {
            printf("Enter the constant term:");
        }
        scanf("%d",&c);
        sum+=c*summation(x,n);
        n--;
    }
    printf("%ld",sum);
    return 0;
}
long summation(int x,int n)
{
    long power;
    if(n==0)
    {
        return 1;
    }
    else
    {
       if(n%2==0)
       {
           power=summation(x,n/2)*summation(x,n/2);
       }
       else
       {
           power=x*summation(x,(n-1)/2)*summation(x,(n-1)/2);
       }
    }
    return power;
}

猜你喜欢

转载自blog.csdn.net/thelostmathematician/article/details/79165716