HDU 1215 七夕節 因數和
阿新 • • 發佈:2018-12-12
Problem Description
七夕節那天,月老來到數字王國,他在城門上貼了一張告示,並且和數字王國的人們說:"你們想知道你們的另一半是誰嗎?那就按照告示上的方法去找吧!" 人們紛紛來到告示前,都想知道誰才是自己的另一半.告示如下:
數字N的因子就是所有比N小又能被N整除的所有正整數,如12的因子有1,2,3,4,6. 你想知道你的另一半嗎?
Input
輸入資料的第一行是一個數字T(1<=T<=500000),它表明測試資料的組數.然後是T組測試資料,每組測試資料只有一個數字N(1<=N<=500000).
Output
對於每組測試資料,請輸出一個代表輸入資料N的另一半的編號.
Sample Input
3 2 10 20
Sample Output
1 8 22
第一種方法跟素數篩法的原理差不多。。。
程式碼如下:
#include <cstdio> #include <cstring> #include <algorithm> #include <iostream> #include <vector> #include <math.h> using namespace std; const int maxn=500005; int a[maxn]; int t,n; void yinzi() { for (int i=1;i<=maxn-5;i++) for (int j=i<<1;j<=maxn-5;j+=i) a[j]+=i; } int main() { yinzi(); scanf("%d",&t); while (t--) { scanf("%d",&n); printf("%d\n",a[n]); } return 0; }
第二種方法是直接暴力。。。
雖然能過,但是耗時太長。。。
程式碼如下:
#include <cstdio> #include <cstring> #include <algorithm> #include <iostream> #include <vector> #include <math.h> using namespace std; const int maxn=500005; int t,n; int ans; int main() { scanf("%d",&t); while (t--) { scanf("%d",&n); ans=0; for (int i=1;i<=sqrt(n);i++) { if(n%i==0) { ans+=i; if(i*i!=n) ans+=(n/i); } } printf("%d\n",ans-n); } return 0; }