素数判断
最大公约数
1.brute-force算法
#include<stdio.h> int main() { int x=30,y=45,z; z=x; while(!(x%z==0&&y%z==0)) z--; printf('%d',z); return 0; }
2.欧几里得算法
穷举法
例 解方程: ①x+y+z=100 ②5x+3y+z/3=100
#include<stdio.h> int main() { int x,y,z; for(x=0;x<=20;x++) for(y=0;y<=33;y++) for(z=0;z<=100;z++) if(x+y+z==100&&5*x+3*y+z/3==100&&z%3==0) printf('x=%d,y=%d,z=%d\n'); return 0; }
级数近似
#include<stdio.h> #include<math.h> int main() { double s=1,a=1,x,eps; int n; scanf('%lf%lf',&x,&eps); for(n=2;fabs(a)>eps;n++){ a=a*x/(n-1); s+=a; } printf('%f',s); return 0; )
一元非线性方程求根
一、牛顿迭代法
1.基本概念:如果函数连续,且待求零点孤立,那么在零点周围存在一个区域,当初值在这个邻域内时,牛顿法收敛。如果零点不为0, 那么牛顿法将具有平方收敛的性能。
2.基本公式:xk+1=xk-f(xk)/f'(xk)
3.判断条件:|f(xn+1)|<ε或|xn+1-xn|<ε是否为真。若为真则xn+1就是方程f(x)=0在x0附近误差ε范围内的一个近似根。
4.实际应用:求cos(x)-x=0的近似解,精确到10-6。
#include<stdio.h> #include<math.h> int main() { double x1=0, x2 = 2; while (fabs(cos(x2)-x2)>1e-6&&fabs(x2-x1)>1e-6){ x1 = x2; x2 = x1 + (cos(x1) - x1) / (sin(x1) + 1); } printf('x=%f\nf(x)=%.6f',x2,fabs(cos(x2)-x2)); return 0; }
二、二分法
1.基本概念:对于区间[a,b]上连续不断且 f(a)f(b)<0的函数y=f(x) ,通过不断地把函数 f(x) 的零点所在的区间一分为二,使区间的两个端点逐步逼近零点,进而得到零点近似值的方法叫二分法。
2.实际应用:求exp(x)+x=0在(-1, 0)的根,精确到10-6。
三、弦截法
1.基本概念:弦截法是求非线性方程近似根的一种线性近似方法。它是以与曲线弧AB对应的弦AB与x轴的交点横坐标作为曲线弧AB与x轴的交点横坐标的近似值μ来求出方程的近似解。
2.实际应用:求((x+2)*x-2)*x-1=0在(-1, 0)的根,精确到10-6。
#include <math.h> #include <stdio.h> float f(float x) { float y; y = ((x + 2.0) * x - 2.0) * x - 1.0; return y; } int main() { float x, x1, x2; x1 = -1, x2 = 0; do{ x = (x1 * f(x2) - x2 * f(x1)) / (f(x2) - f(x1)); if (f(x) * f(x1) > 0) x1 = x; else x2 = x; } while (fabs(f(x)) >= 1e-6); printf('the root is %f\n', x); printf('((x+2.0)*x-2.0)*x-1.0=%f\n', f(x)); return 0; }
定积分近似计算
1.梯形法
算法思想
程序实现
2.矩形法
算法思想
程序实现
#include<stdio.h> #include<math.h> int main() { long n,i; double a=-1.57,b=1.57,h,s=0,x; scanf('%ld',&n); h=(b-a)/n; x=a; for(i=0;i<n;i++){ s+=cos(x); x+=h; } printf('%f',s*h); return 0; }
联系客服