数据结构01秦九算法

	int a[10]; 
	int n=10,x;
	cin >> x;
	int sum=0;
	//一般算法
	for (int i = 0; i < n;i++)
	{
		sum += a[i] * pow(x, i);
	}
	sum = 0;
	//秦九韶算法
	for (int i = n-1; i >=0; i--)
	{
		sum += sum*x + a[n - 1];
	}

普通算法运行时间为 n(n+1)/2次乘法+N次加法

秦九韶算法:n次乘法和n次加法

(求 a0*x^0+a1*x^1+a2*x^2+.....+an*x^n)

2求最大子列

	int a[10];
	int n = 10;
	int sum = 0;
	int thissum = 0;
	//没优化,n^3
	for (int i = 0; i < n;i++)
	{
		for (int j = i; j < n; j++)
		{
			thissum = 0; 
			for (int k = i; k < j; k++)
			{
				thissum += a[k];
			}
			if (thissum>sum)
			{
				sum = thissum;
			}
		}
	}
	//一次优化之后,O(n)=n^2
	for (int i = 0; i < n; i++)
	{
		thissum = 0;
		for (int j = i; j < n; j++)
		{
			thissum += a[j];
			if (thissum>sum)
			{
				sum = thissum;
			}
		}
	}
	//第三次优化,分治法


断电,明天更
在C语言中,要计算多项式P(x)=1+x+2x²+…+7x^7在x=1的值,可以使用以下三种方法: 1. 计算一项累加一项: 这种方法是从第一项开始,逐项计算多项式的值,然后将每一项的结果累加起来。这种方法简单直观,但效率不是最高,尤其是当多项式的次数非常高时。 ```c #include <stdio.h> double polynomial_one_by_one(int x, int terms) { double result = 0.0; for (int i = 0; i < terms; i++) { result += (i + 1) * pow(x, i); // 系数为i+1,x的i次幂 } return result; } int main() { int x = 1; int terms = 7; double result = polynomial_one_by_one(x, terms); printf("多项式的值为: %f\n", result); return 0; } ``` 2. 高乘幂继承低乘幂: 这种方法从最高次幂开始计算,每次计算新的项时,都利用上一次计算的结果,这样可以减少重复计算。对于本题中的多项式,可以用这种方法来提高效率。 ```c #include <stdio.h> double polynomial_high_power_low_power(int x, int terms) { double result = 0.0; double base = 1.0; // 0次幂为1 for (int i = 0; i <= terms; i++) { result += (i + 1) * base; // 系数为i+1,使用上一次的base值 base *= x; // 继承低乘幂 } return result; } int main() { int x = 1; int terms = 7; double result = polynomial_high_power_low_power(x, terms); printf("多项式的值为: %f\n", result); return 0; } ``` 3. 秦九算法秦九算法是一种更高效的多项式求值方法,使用了多项式求值的最优形式。这种方法不是简单的递增或递减,而是在每个步骤中都进行最优的选择,以减少乘法的次数。 对于本题的多项式,秦九算法的直接应用比较复杂,因为它通常用于多项式的快速求值问题,如霍纳法则(Horner's Rule),但秦九算法的原理可以帮助我们更好地理解如何优化多项式求值的计算过程。 使用霍纳法则,也就是秦九算法的简化版本,对于本题多项式可以如下实现: ```c #include <stdio.h> double polynomial_horner(int x, int terms) { double result = 1.0; // 从x^0开始 for (int i = 1; i <= terms; i++) { result = result * x + i; // 逐步计算多项式的值 } return result; } int main() { int x = 1; int terms = 7; double result = polynomial_horner(x, terms); printf("多项式的值为: %f\n", result); return 0; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值