您的位置:首页 > 其它

欧拉项目 第21题 Amicable numbers

2016-03-18 11:34 369 查看
Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n).

If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable pair and each of a and b are called amicable numbers.
For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220.
Evaluate the sum of all the amicable numbers under 10000.

x的所有因子(不含x)之和为y,y的因子(不含y)为x,
求小于10000,满足上述条件的数的和。

static Map<Integer, HashSet<Integer>> map = new HashMap<Integer, HashSet<Integer>>();//存放已求的数的因子集

static Map<Integer, Integer> sum_ = new HashMap<Integer, Integer>(); //存放已求的数的因子和

static List<Integer> sz = new ArrayList<Integer>();//存放已匹配符合条件的值

public static void main(String[] args) {
long start = System.currentTimeMillis();
int num = 0;
for(Integer i=2;i<10000;i++) {
if(sz.contains(i)) {
continue;
}
Integer this_ = getSum(i);
if(this_.compareTo(i) == 0) {
continue;
}
Integer next_ = getSum(this_);
if(i.compareTo(next_) == 0) {
sz.add(i);
sz.add(this_);
num+=i;
num+=this_;
//System.out.println(i + " " + this_);
}
}
System.out.println(System.currentTimeMillis() - start);
System.out.println(num);

}

//求因子和
static Integer getSum(Integer val){
if(sum_.get(val) != null) {
return sum_.get(val);
}
HashSet<Integer> x = get(val);
Integer this_ = 0;
for(Integer x1 : x) {
if(x1 != val) {
this_ += x1;
}
}
sum_.put(val, this_);
return this_;
}

//求因子
static HashSet<Integer> get(Integer val) {
if(map.get(val) != null) {
return map.get(val);
}
HashSet<Integer> th = new HashSet<Integer>();
th.add(1);
th.add(val);
for(int i=2;i<=Math.sqrt(val);i++) {
if(val%i==0) {
th.add(i);
int y = val/i;
th.add(y);
if(val%i != i) {
if(map.get(y) != null) {
th.addAll(map.get(y));
}
}
}
}
map.put(val, th);
return th;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: