PE Problem 95 Amicable chains (分解因子和)

Amicable chains

Problem 95

The proper divisors of a number are all the divisors excluding the number itself. For example, the proper divisors of 28 are 1, 2, 4, 7, and 14. As the sum of these divisors is equal to 28, we call it a perfect number.

Interestingly the sum of the proper divisors of 220 is 284 and the sum of the proper divisors of 284 is 220, forming a chain of two numbers. For this reason, 220 and 284 are called an amicable pair.

Perhaps less well known are longer chains. For example, starting with 12496, we form a chain of five numbers:

12496 → 14288 → 15472 → 14536 → 14264 (→ 12496 → ...)

Since this chain returns to its starting point, it is called an amicable chain.

Find the smallest member of the longest amicable chain with no element exceeding one million.



代码:

转为Java选手....

import java.util.ArrayList;

public class Main
{
	static int sum_Of_Divisors(int n)
	{
		int exclude = n;
		int sum = 1;
		for(int i = 2; (i * i) <= n; i++)
		{
			int p = 1;
			while(n % i == 0)
			{
				p = p * i + 1;
				n /= i;
			}
			sum *= p;
		}
		if(n > 1)
			sum *= 1 + n;
		return sum - exclude;
	}
	
	static int findMin(ArrayList<Integer> list)
	{
		int min = list.get(0);//取下标为0的元素
		for(int i = 1; i < list.size(); i++)
			min = list.get(i) < min ? list.get(i):min;
		return min;
	}
	
	public static void main(String[] args)
	{
		int maxChain = 0;
		int result = 0;
		for(int i = 1; i < 1000000; i++)
		{
			ArrayList<Integer> amicableChains = new ArrayList<Integer>();
			int n = i;
			while(true)
			{
				amicableChains.add(n);//往链中增加元素n
				n = sum_Of_Divisors(n); //分解因子和
				if(n == i && amicableChains.size() > maxChain) //链是至今最长的
				{
					maxChain = amicableChains.size();
					result = findMin(amicableChains);
				}
				if(amicableChains.contains(n) || n > 1000000)//回到起点或者n>1000000
					break;
			}
		}
		System.out.println(result);
	}	
}



  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值