16行代码AC——紫书| 例题7-3 Fractions Again?! (UVA - 10976)_时间复杂度O(n)
勵志用盡量少的代碼做高效表達
Problem describe
It is easy to see that for every fraction in the form 1/k(k > 0), we can always find two positive integers x and y, x ≥ y, such that:1/k=1/x+1/y1/k=1/x+1/y1/k=1/x+1/y
Now our question is: can you write a program that counts how many such
pairs of x and y there are for any given k?
Input
Input contains no more than 100 lines, each giving a value of k(0 < k ≤ 10000).
Output
For each k, output the number of corresponding (x, y) pairs, followed by a sorted list of the > values of x and y, as shown in the sample output.
Sample Input
2
12
Sample Output
2
1/2 = 1/6 + 1/3
1/2 = 1/4 + 1/4
8
1/12 = 1/156 + 1/13
1/12 = 1/84 + 1/14
1/12 = 1/60 + 1/15
1/12 = 1/48 + 1/16
1/12 = 1/36 + 1/18
1/12 = 1/30 + 1/20
1/12 = 1/28 + 1/21
1/12 = 1/24 + 1/24
題目(提交)鏈接——>UVa-10976
心路歷程
題目不難理解,比較難的是如何更好的A掉,最近在備考藍橋杯,因此十分注重對暴力枚舉的理解和優化。
當n=9999時,暴力枚舉顯然可能超限,因此放棄。
觀察樣例時發現,由于有x>=y的規定,因此y的最大值只能是n/2。而y的最小只能取到n+1。這樣,y的范圍就出來了,接下來考慮x。
我們發現,如果y等于一個不合適的數,顯然x增大到無限大也沒辦法得出解,因此得設法固定住x。
于是我將x設為未知數。很容易列出方程:
1/n=1/y+1/x1/n = 1/y + 1/x 1/n=1/y+1/x
化簡后得:
n?y=(y?n)?xn*y=(y-n)*xn?y=(y?n)?x
其中y、n已知,不難得出,x=(n*y)/(y-n)。
在y的遍歷過程中,若x為整數,則說明有解,直接輸出即可。
在編寫代碼過程中,我使用了兩個動態數組vector,求長度、動態存儲等更方便一些。
代碼展示:
#include<bits/stdc++.h> using namespace std; int main() {int n; while(scanf("%d", &n) != EOF) {vector<int>v1, v2; //分別存儲分子和分母 v1.clear(); v2.clear(); for(int i = n*2; i > n; i--) if((i*n)%(i-n)==0) {v1.push_back(i); v2.push_back((i*n)/(i-n)); } //輸出 int len = v1.size();printf("%d\n", len);for(int i=(len-1); i>=0; i--) printf("1/%d = 1/%d + 1/%d\n", n, v2[i], v1[i]); } return 0; }總結:
數學是編程中非常重要的一環,雖然編程題中直接涉及的數學知識不算很多,但靈活的應用數學思想,絕對會使編程水平有質的提高。
如果這篇文章對你產生了幫助,就請給博主一個小小的贊吧!大家的點贊是我創作的最大動力!
總結
以上是生活随笔為你收集整理的16行代码AC——紫书| 例题7-3 Fractions Again?! (UVA - 10976)_时间复杂度O(n)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 43行代码AC_HDU-2604 Que
- 下一篇: 38行代码AC——UVA-167The