看英语不是太懂,最后看了它们的解题思路。
1 #include <iostream> 2 using namespace std; 3 4 typedef long long ll; 5 6 ll gcd(ll a, ll b) { 7 if (b == 0) return a; 8 gcd(b, a%b); 9 } 10 11 int digits(ll a) { 12 int cnt = 0; 13 while (a > 9 || a % 10 != 0) { 14 cnt++; 15 a = a / 10; 16 } 17 return cnt; 18 } 19 20 ll fenmu(int n) { 21 ll sum = 1; 22 for (int i = 1; i <= n; i++) 23 sum = sum*i/gcd(sum, i); 24 return sum; 25 } 26 27 ll fenzi(int n) { 28 ll tmp = fenmu(n); 29 ll sum = 0; 30 for (int i = 1; i <= n; i++) 31 sum = sum+tmp / i; 32 return n*sum; 33 } 34 35 int main() { 36 int n; 37 while (cin >> n) { 38 ll fm = fenmu(n); 39 ll fz = fenzi(n); 40 ll zs = fz / fm; 41 fz %= fm; 42 if (fz%fm == 0) { 43 cout << zs << endl; 44 continue; 45 } 46 47 int ws = digits(zs); 48 for (int i = 0; i <= ws; i++) 49 cout << " "; 50 51 52 int tmp = gcd(fz, fm); 53 while (tmp!= 1) { 54 fz /= tmp; 55 fm /= tmp; 56 tmp = gcd(fz, fm); 57 } 58 cout << fz << endl; 59 60 cout << zs << " "; 61 ws = digits(fm); 62 for (int i = 0; i < ws; i++) 63 cout << "-"; 64 cout << endl; 65 66 ws = digits(zs); 67 68 for (int i = 0; i <= ws; i++) 69 cout << " "; 70 cout << fm << endl; 71 } 72 }