HDU 七夕节(打表)

打表做,用一个数组存储数据要求范围内的所有数值的因子之和。第一层循环枚举所有因子,第二层循环把每个该因子倍数的数累加。不断刷新表的值,直到最后更新完毕。

例:2 - 9数值范围内的每个数的因子之和

因为因子不包括本身,所以本身不算是倍数
因子1的倍数 因子2的倍数 因子3的倍数 因子4的倍数
table[2] = 1  table[4] = 1 + 2 = 3  table[6] = 3 + 3 = 6  table[8] = 3 + 4 = 7
table[3] = 1  table[6] = 1 + 2 = 3  table[9] = 1 + 3 = 4
table[4] = 1  table[8] = 1 + 2 = 3
table[5] = 1
table[6] = 1
table[7] = 1
table[8] = 1
table[9] = 1

 1 #include <cstdio>
 2 #include <iostream>
 3 using namespace std;
 4 
 5 #define MAX 500010
 6 static int table[MAX] = {0};
 7 
 8 void Table()
 9 {
10     for (int i = 1; i < MAX / 2; i++)
11     {
12         for (int j = i + i; j < MAX; j += i)
13         {
14             table[j] += i;
15         }
16     }
17 }
18 
19 int main()
20 {
21     Table();
22     int n;
23     scanf("%d", &n);
24     while (n--)
25     {
26         int x;
27         scanf("%d", &x);
28         printf("%d\n", table[x]);
29     }
30     return 0;
31 }

刚开始使用普通做法,超时。。。代码如下:

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cmath>
 4 #include <cstring>
 5 using namespace std;
 6 
 7 int Find(int n)
 8 {
 9     int x = n / 2;
10     int sum = 0;
11     for (int i = 1; i <= x; i++)
12     {
13         if (n % i == 0)
14         {
15             sum += i;
16         }
17     }
18     return sum;
19 }
20 
21 int main(void)
22 {
23     int t;
24     scanf("%d", &t);
25     while (t--)
26     {
27         int n;
28         scanf("%d", &n);
29         int res = Find(n);
30         printf("%d\n", res);
31     }
32     return 0;
33 }

 

转载于:https://www.cnblogs.com/changeFeng/p/9338559.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值