NOIp2014 Day2T3 解方程 秦九韶算法
a0+a1*x+a2*x^2+a3*x^3...+an*x^n
=a0+x*(a1+x*(a2+x*(a2+...+x*(an+0) ) ) )
正好可以递归计算。
一个小技巧是过程在一个大质数的同余系中计算,没有降低太多正确性,却避免了高精度。(重要)
1 #include<iostream> 2 #include<cstdio> 3 using namespace std; 4 typedef long long ll; 5 6 const int mod = 1e9+7; 7 ll a[110],s[1000010]; 8 ll m,n,top; 9 10 ll read(){ 11 ll a = 0;char c = getchar(),l = c; 12 while(c < '0'||c > '9')l = c,c = getchar(); 13 while('0' <= c&&c <= '9') 14 a = (a*10+c-'0')%mod,c = getchar(); 15 if(l == '-')return -a; return a; 16 } 17 18 bool check(ll x){ 19 ll s = 0; 20 for(int i = n;i >= 0;i--)s = (s*x+a[i])%mod; 21 return !s; 22 } 23 24 int main(){ 25 cin >> n >> m; 26 for(int i = 0;i <= n;i++)a[i] = read(); 27 for(int i = 1;i <= m;i++)if(check(i)) 28 s[++top] = i; 29 printf("%lld\n",top); 30 for(int i = 1;i <= top;i++)printf("%lld\n",s[i]); 31 return 0; 32 }