package cn.javass.mytest.java.euler; import java.util.Set; import java.util.TreeSet; /** * a(b) 表示 a的b次方 * * Consider all integer combinations of ab for 2<=a<=5 and 2<=b<=5: 2(2)=4, 2(3)=8, 2(4)=16, 2(5)=32 3(2)=9, 3(3)=27, 3(4)=81, 3(5)=243 4(2)=16, 4(3)=64, 4(4)=256, 4(5)=1024 5(2)=25, 5(3)=125, 5(4)=625, 5(5)=3125 If they are then placed in numerical order, with any repeats removed, we get the following sequence of 15 distinct terms: 4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125 How many distinct terms are in the sequence generated by a(b) for 2<=a<=100 and 2<=b<=100? * @author wangxm * * 分析:a、b为一百以内。一百以内的n次方数(可以写成a的b次方的数)为以下数列。 * 也只有这些数(以这些数为底计算)存在重复的可能性。 * 4, 8, 9, 16, 25, 27, 32, 36, 49, 64, 81 100 * 2(2),2(3),3(2),4(2),5(2),3(3),2(5),6(2),7(2),2(6),9(2),10(2) */ public class Problem29 { //使用set存储这些幂对象。剔除重复项 static Set<Power> numSet = new TreeSet<Power>(); static void initSet(){ for(int x=2;x<=100;x++){ for(int y=2;y<=100;y++){ switch (x){ case 4: case 9: case 25: case 36: case 49: case 100: numSet.add(new Power((int)Math.sqrt(x),y*2)); break; case 81: numSet.add(new Power(3,y*4)); break; case 27: numSet.add(new Power(3,y*3)); break; case 8: numSet.add(new Power(2,y*3)); break; case 16: numSet.add(new Power(2,y*4)); break; case 32: numSet.add(new Power(2,y*5)); break; case 64: numSet.add(new Power(2,y*6)); break; default: numSet.add(new Power(x,y)); } } } } public static void main(String[] args) { long beginTime = System.currentTimeMillis(); initSet(); // System.out.println(numSet); System.out.println(numSet.size());//9183 long endTime = System.currentTimeMillis();//31ms System.out.println(endTime-beginTime+"ms"); } } //构建幂(类),底数为x,指数为y class Power implements Comparable<Power>{ private int x; private int y; public Power(int x,int y){ this.x=x; this.y=y; } @Override public int hashCode() { final int PRIME = 31; int result = 1; result = PRIME * result + x; result = PRIME * result + y; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final Power other = (Power) obj; if (x != other.x) return false; if (y != other.y) return false; return true; } public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; } //实现compareTo方法,用于对象比较。 public int compareTo(Power o) { if(this.equals(o)){ return 1; }else if(this.equals(o)){ return 0; }else{ return -1; } } public String toString(){ return "x:"+this.x+" y:"+this.y; } }