2-06. 数列求和
时间限制
50 ms
内存限制
32000 kB
代码长度限制
8000 B
判题程序
Standard
http://pat.zju.edu.cn/contests/ds/2-06
给定某数字A(1<=A<=9)以及非负整数N(0<=N<=100000),求数列之和S = A + AA + AAA + … + AA…A(N个A)。例如A=1, N=3时,S = 1 + 11 + 111 = 123。
输入格式说明:
输入数字A与非负整数N。
输出格式说明:
输出其N项数列之和S的值。
样例输入与输出:
序号 输入 输出 1 1 3
123
2 6 100
7407407407407407407407407407407407407407407407407407407407407407407407407407407407407407407407407340
3 1 0
0
这道题目一直超时,刚开始用的是java写的,刚开始以为是大整数问题,所以就直接利用java.Math里面的BigInteger类来完成,结果超时了
初始代码:
import java.util.*;
import java.math.BigInteger;
class Main
{
public static void main(String[] args)
{
int a,n;
Scanner sc = new Scanner(System.in);
char aaa = '0';
System.out.println((int)aaa);
while(sc.hasNextInt())
{
a = sc.nextInt();
n = sc.nextInt();
long t = System.currentTimeMillis();
BigInteger bi = new BigInteger(String.format("%d",a));
BigInteger temp = new BigInteger(String.format("%d",a));
BigInteger biSum = BigInteger.ZERO;
for(int i = 0;i<n;i++)
{
biSum = biSum.add(temp);
temp = temp.multiply(BigInteger.TEN);
temp =temp.add(bi);
}
System.out.println(biSum.toString());
System.out.println(System.currentTimeMillis()-t);
}
}
}
以6 100为例运行时间是17ms 6 100
74074074074074074074074074074074074074074074074074074074074074074074074074074074
07407407407407407340
17
第二种是:
import java.util.*;
import java.math.BigInteger;
class Main2
{
public static void main(String[] args)
{
int a,n;
Scanner sc = new Scanner(System.in);
//char aaa = '0';
// System.out.println((int)aaa);
while(sc.hasNextInt())
{
a = sc.nextInt();
n = sc.nextInt();
long t = System.currentTimeMillis();
BigInteger bi = new BigInteger(String.format("%d",a));
BigInteger temp = new BigInteger(String.format("%d",a));
BigInteger biSum = BigInteger.ZERO;
for(int i = 0;i<n;i++)
{
biSum = biSum.add(temp);
temp = temp.multiply(BigInteger.TEN);
temp =temp.add(bi);
}
System.out.println(biSum.toString());
System.out.println(System.currentTimeMillis()-t);
}
}
}
第三种方法:采用技巧,把所有数进行累加,好像把所有数手算的时候把所有的数进行相加! import java.util.Scanner;
class Main3
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int[] sum = new int[100000];
int mod = 0;
int i;
int a = sc.nextInt();
int n = sc.nextInt();
long l = System.currentTimeMillis();
if(n==0)
{
System.out.println(0);
return;
}
for(i =0;i<n||(i>=n&&mod!=0);i++)
{
sum[i] = (a*(n-i)+mod)%10;
mod = (a*(n-i)+mod)/10;
}
for(int j =i-1;j>=0;j--)
{
System.out.print(sum[j]);
}
System.out.printf("\n");
System.out.println(System.currentTimeMillis()-l);
}
}
第三种方法应该是最优的了,可是还是超时,怒用C++ #include<stdio.h>
int main()
{
int sum[100010];
int a,n;
scanf("%d%d",&a,&n);
int i,mod;
if(n==0)
{
printf("0\n");
return 0;
}
for(i =0;i<n||(i>=n&&mod!=0);i++)
{
sum[i] = (a*(n-i)+mod)%10;
mod = (a*(n-i)+mod)/10;
}
for(int j =i-1;j>=0;j--)
{
printf("%d",sum[j]);
}
printf("\n");
return 0;
}
好的,通过了,看来PAT没有给java双倍时间啊,无力吐槽