HDOJ1041
用C++写了一遍:
#include <iostream>
#include <cstring>
#include<sys/timeb.h>
using namespace std;
int Result[1002][500],len[1002];
int k;
void Calc(int t)
{
int i,j;
len[k]=len[k-1];
for(i=0;i<=len[k];i++)
Result[k][i]=Result[k-1][i]*2;
Result[k][0]+=t;
if(Result[k][0]<0)
{
Result[k][0]=10+Result[k][0];
j=1;
while(Result[k][j]==0)j++;
Result[k][j]-=1;
}
for(j=0,i=0;i<=len[k];i++)
{
Result[k][i]+=j;
j=Result[k][i]/10;
Result[k][i]%=10;
}
if(j!=0)
Result[k][++len[k]]=j;
}
void Solve()
{
int t=1;
memset(len,0,sizeof(len));
memset(Result,0,sizeof(Result));
for(k=2;k<=1000;k++,t*=(-1))
Calc(t);
}
int main()
{
int n;
//timeb t1,t2;
//long TotalTime;
//ftime(&t1);
Solve();
/*ftime(&t2); //记录打表后的时间
TotalTime=(t2.time-t1.time)*1000+(t2.millitm-t1.millitm);
cout<<TotalTime<<endl; */
while(cin>>n)
{
for(int i=len[n];i>=0;i--)
cout<<Result[n][i];
cout<<endl;
}
return 0;
}
#include <cstring>
#include<sys/timeb.h>
using namespace std;
int Result[1002][500],len[1002];
int k;
void Calc(int t)
{
int i,j;
len[k]=len[k-1];
for(i=0;i<=len[k];i++)
Result[k][i]=Result[k-1][i]*2;
Result[k][0]+=t;
if(Result[k][0]<0)
{
Result[k][0]=10+Result[k][0];
j=1;
while(Result[k][j]==0)j++;
Result[k][j]-=1;
}
for(j=0,i=0;i<=len[k];i++)
{
Result[k][i]+=j;
j=Result[k][i]/10;
Result[k][i]%=10;
}
if(j!=0)
Result[k][++len[k]]=j;
}
void Solve()
{
int t=1;
memset(len,0,sizeof(len));
memset(Result,0,sizeof(Result));
for(k=2;k<=1000;k++,t*=(-1))
Calc(t);
}
int main()
{
int n;
//timeb t1,t2;
//long TotalTime;
//ftime(&t1);
Solve();
/*ftime(&t2); //记录打表后的时间
TotalTime=(t2.time-t1.time)*1000+(t2.millitm-t1.millitm);
cout<<TotalTime<<endl; */
while(cin>>n)
{
for(int i=len[n];i>=0;i--)
cout<<Result[n][i];
cout<<endl;
}
return 0;
}
再用Java写了一遍:
import java.util.*;
import java.math.*;
public class Main
{
public static void main(String[] args)
{
BigInteger []str = new BigInteger[1002];
BigInteger a = BigInteger.valueOf(1);
BigInteger b = BigInteger.valueOf(2);
str[0] = str[1] = BigInteger.valueOf(0);
int n;
for(int i = 2; i <= 1000; i++)
{
str[i]= str[i - 1].multiply(b);
if(i % 2 == 0)
str[i] = str[i].add(a);
else
str[i] = str[i].subtract(a);
}
Scanner cin = new Scanner(System.in);
while(cin.hasNextInt())
{
n = cin.nextInt();
System.out.println(str[n]);
}
}
}
import java.math.*;
public class Main
{
public static void main(String[] args)
{
BigInteger []str = new BigInteger[1002];
BigInteger a = BigInteger.valueOf(1);
BigInteger b = BigInteger.valueOf(2);
str[0] = str[1] = BigInteger.valueOf(0);
int n;
for(int i = 2; i <= 1000; i++)
{
str[i]= str[i - 1].multiply(b);
if(i % 2 == 0)
str[i] = str[i].add(a);
else
str[i] = str[i].subtract(a);
}
Scanner cin = new Scanner(System.in);
while(cin.hasNextInt())
{
n = cin.nextInt();
System.out.println(str[n]);
}
}
}