程序代码:
/* 手工开根号:<span style="color: #008000; text-decoration: underline;">http://wenku.baidu.com/view/e048aa651eb91a37f1115c16.html[/color] */ #include <stdio.h> #define LEN_RESULT 100 #define LEN 102 int comp(int *a, int *b, int n) { //return a > b; int i; for (i = n;i <= 2*n+1;++i) { if (a[i] < b[i]) return 0; if (a[i] > b[i]) return 1; } return 0; } /* 其实可以写乘法的,这里是变乘为加, 以为会更好写,结果画蛇添足 (20a+n+1)*(n+1) - (20a+n)*n = 20a+2*n+1 */ void add(int *a, int *b, int *c, int n, int m) { int i, j, res = 0; for (i = n*2+1;i >= n;c[i] = a[i], --i); for (i = n*2, j = n-1;j >= 0;--i, --j) { res += c[i] + b[j] * 2; c[i] = res % 10, res /= 10; } while (res) c[i--] += res % 10, res /= 10; i = n * 2 + 1, res = m * 2 + 1; while (res) { res += c[i]; c[i--] = res % 10, res /= 10; } } void sub(int *a, int *b, int n) { int i, j; for (i = n*2+1;i >= n;--i) { a[j = i] -= b[i]; while (a[j] < 0) a[j] += 10, --a[--j]; } } /* 得到 结果 a的第 n位,试商。 tmp[n] = (20a + n) * n */ int get_ans(int *a, int *b, int n) { int i, j, tmp[10][LEN*2] = {0}; for (i = n*2, j = n-1;j >= 0;--i, --j) tmp[0][i] = a[j] * 2; tmp[0][n*2+1] = 1; if (comp(tmp[0], b, n)) return 0; for (i = 1;i < 10;++i) { add(tmp[i-1], a, tmp[i], n, i); if (comp(tmp[i], b, n)) break; } sub(b, tmp[i-1], n); return i; } void fun(int *a, int *b) { int i; //a = sqrt(5); for (i = 0;i <= LEN_RESULT;++i) { a[i] = get_ans(a, b, i); } //ans = ( sqrt(5) - 1 ) / 2 for (a[0]--, i = 0;i < LEN_RESULT;++i) { a[i+1] += (a[i] % 2) * 10; a[i] /= 2; } } int main() { int i, ans[LEN] = {0}; int s[LEN*2] = {0, 5}; fun(ans, s); for (i = 0; i < LEN_RESULT;++i) printf("%d", ans[i]); printf("\n"); return 0; }
[fly]存在即是合理[/fly]