# 分数 1/1 + 1/2 + 1/4 + 1/8 + 1/16 + … 每项是前一项的一半,如果一共有20项,求这个和是多少,结果用分数表示出来。 类似:3/2 当然,这只是加了前2项而已。分子分母要求互质。 下面哪一项是错误的? ## aop ### before ```c #include using namespace std; ``` ### after ```c ``` ## 答案 ```c long pow_2(int b) { long x = 2; long res = 1; while (b > 0) { if (b & 1) res *= x; b >>= 1; x = x * x; } return res; } int gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } int main() { cout << pow_2(20) << "/" << pow_2(19) << endl; } ``` ## 选项 ### A ```c long pow_2(int b) { long x = 2; long res = 1; while (b > 0) { if (b & 1) res *= x; b >>= 1; x = x * x; } return res; } int gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } int main() { cout << pow_2(20) - 1 << "/" << pow_2(19) << endl; } ``` ### B ```c int gcd(int a, int b) { return a % b ? gcd(b, a % b) : b; } int main() { int a = 1048575, b = 524288; int t = gcd(a, b); cout << a / t << "/" << b / t << endl; return 0; } ``` ### C ```c int gcd(int a, int b) { while (b > 0) { int c; c = a % b; a = b; b = c; } return a; } int main() { int a = 1048575; int b = 524288; int c = gcd(a, b); cout << a / c << "/" << b / c << endl; return 0; } ```