本文主要是介绍PIPIOJ 1043 数学王子,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
我的解法:
#include<iostream>
#include<cmath>
using namespace std;double calculate(int num)//1+2+……+10n
{double max = pow(10, num);double sum = 0;for (double i = 1; i <= max; i++){sum = sum + i;}return sum;
}int main()
{int n = 0;cin >> n;int* p = new int[n];for (int i = 0; i < n; i++){cin>>p[i];}for (int i = 0; i < n; i++){cout << calculate(p[i]) << endl;}return 0;
}
结果:时间超限
正解:
【思路】取比较小的n发现规律如下,直接按照规律得出结果,而非计算。
10
0
1
1
55
2
5050
3
500500
4
50005000
5
5000050000
6
500000500000
7
50000005000000
8
5000000050000000
9
500000000500000000......
#include<stdio.h>
#include<math.h>
int main(void)
{int n,m;scanf("%d",&n);for(int i=1;i<=n;i++){scanf("%d",&m);if(m==0){printf("%d\n",1);continue;}if(m==1){printf("%d\n",55);continue;}printf("%d",5);for(int j=1;j<m;j++){printf("%d",0);}printf("%d",5);for(int j=1;j<m-1;j++){printf("%d",0);}printf("%d\n",0);}return 0;
}
C++版本:
#include<iostream>
#include<cmath>
#include<string>
using namespace std;int main()
{//求1+2+...+10^nint n = 0;cin >> n;int* p = new int[n];for (int i = 0; i < n; i++){cin >> p[i];}for (int i = 0; i < n; i++){if (p[i] == 0){cout << 1 << endl;}else{string temp = "5";for (int j = 0; j < p[i]-1; j++){temp = temp + "0";}temp = temp + temp;cout << temp << endl;}}return 0;
}
这篇关于PIPIOJ 1043 数学王子的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!