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
 
 1 #include <stdio.h>
 2 #include <string.h>
 3 #define N 500000
 4 int a[N + 5];
 5 int main()
 6 {
 7     int T, num, i, j, k;
 8     scanf("%d", &T);
 9     //firstly, initialize the array
10     a[1] = 0;
11     for (k = 2; k <= N; k++)
12         a[k] = 1;
13     //secondly, handle the array
14     for (i = 2; i <= N / 2; i++)
15     {
16         for (j = 2 * i; j <= N; j += i)
17             a[j] += i;
18     }
19     //last, get the answer by input
20     while (T--)
21     {
22         scanf("%d", &num);
23         printf("%d\n", a[num]);
24     }
25     return 0;
26 }
Core algorithm:
in order to make the O(n^2) to O(n), we use the above algorithm.
firstly, make the first number is zero and the other numbers in array equal to one.
then, traverse the array, make the multiple of every number in array to plus the number.
lastly, get the answer by input.
 
pay more attention to good algorithm.
Good luck!
posted on 2012-10-17 10:33  MrMission  阅读(510)  评论(0编辑  收藏  举报