2013
11-12

# Fermat’s Christmas Theorem

In a letter dated December 25, 1640; the great mathematician Pierre de Fermat wrote to Marin Mersenne that he just proved that an odd prime p is expressible as p = a2 + b2 if and only if p is expressible as p = 4c + 1. As usual, Fermat didn’t include the proof, and as far as we know, never wrote it down. It wasn’t until 100 years later that no one other than Euler proved this theorem. To illustrate, each of the following primes can be expressed as the sum of two squares:

 5 = 22 + 12 13 = 32 + 22 17 = 42 + 12 41 = 52 + 42

Whereas the primes 11, 19, 23, and 31 cannot be expressed as a sum of two squares. Write a program to count the number of primes that can be expressed as sum of squares within a given interval.

Your program will be tested on one or more test cases. Each test case is specified on a separate input line that specifies two integers L, U where LU < 1,000,000.

The last line of the input file includes a dummy test case with both L = U = −1.

For each test case, write the result using the following format:

L U x y

where L and U are as specified in the input. x is the total number of primes within the interval [L, U] (inclusive), and y is the total number of primes (also within [L, U]) that can be expressed as a sum of squares.

10 20
11 19
100 1000
-1 -1

10 20 4 2
11 19 4 2
100 1000 143 69

//* @author  mekarlos@gmail.com
import java.io.IOException;
import java.util.StringTokenizer;

public class Main {
public static void main(String args[]) throws IOException{
StringTokenizer tokens;
int[] prims=new int[1000001];
int[] ferms=new int[1000001];
for(int i=3;i< 1000000;i+=2)
prims[i]=1;
prims[2]=1;
int index=1;
while((index+=2)< 1000000)
if(prims[index]==1)
for(int i=2*index;i< 1000000;i+=index) prims[i]=0;
ferms[2]=1;
for(int i=3;i< 1000000;i+=2){
if(prims[i]==1&&i%4==1) ferms[i]=1;
prims[i]+=prims[i-1];
prims[i+1]=prims[i];
ferms[i]+=ferms[i-1];
ferms[i+1]=ferms[i];
}
int limi=0,lims=0,in,su;
while(true){
limi=Integer.parseInt(tokens.nextToken());
lims=Integer.parseInt(tokens.nextToken());
if(limi==-1&&lims==-1) break;
in=limi;
su=lims;
if(limi<=0) limi=1;
if(lims<=0) lims=1;
System.out.println(in+" "+su+" "+(prims[lims]-prims[limi-1])+" "+(ferms[lims]-ferms[limi-1]));
}
}
}

1. 给你一组数据吧：29 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 1000。此时的数据量还是很小的，耗时却不短。这种方法确实可以，当然或许还有其他的优化方案，但是优化只能针对某些数据，不太可能在所有情况下都能在可接受的时间内求解出答案。

2. 约瑟夫也用说这么长……很成熟的一个问题了，分治的方法解起来o(n)就可以了，有兴趣可以看看具体数学的第一章，关于约瑟夫问题推导出了一系列的结论，很漂亮

3. 学算法中的数据结构学到一定程度会乐此不疲的，比如其中的2－3树，类似的红黑树，我甚至可以自己写个逻辑文件系统结构来。

4. 我还有个问题想请教一下，就是感觉对于新手来说，递归理解起来有些困难，不知有没有什么好的方法或者什么好的建议？