关闭

110706 Smith Numbers

标签: 编程
310人阅读 评论(0) 收藏 举报
分类:


import java.util.*;
import static java.lang.Math.*;

public class Main {
	private static List<Long> s_Primes;
	
	static
	{
		s_Primes = new LinkedList<Long>();
		s_Primes.add(2L);
		long limit = (long)sqrt(2000000000L) + 1;
		for (long i = 3L; i <= limit; i += 2L)
		{
			long mid = (long)sqrt(i);
			Iterator<Long> iter = s_Primes.iterator();
			
			boolean isPrime = true;
			while (iter.hasNext())
			{
				long x = iter.next();
				if (x > mid)
					break;
				
				if ((i % x) == 0)
				{
					isPrime = false;
					break;
				}
			}
			
			if (isPrime)
				s_Primes.add(i);
		}
	}
	
	private static List<Long> GetAllPrimeElements(long number)
	{		
		List<Long> result = new LinkedList<Long>();
		Iterator<Long> iter = s_Primes.iterator();
		boolean canTryNext = true;
		long mid = (long)sqrt(number);
		long i = 0;
		while (number > 1)
		{
			if (canTryNext)
			{
				if (!iter.hasNext())
				{
					result.add(number);
					return result;
				}
				
				i = iter.next();
				if (i > mid)
				{
					result.add(number);
					return result;
				}
			}
			
			if ((number % i) == 0)
			{
				canTryNext = false;
				number /= i;
				mid = (long)sqrt(number);
				result.add(i);
			}
			else
				canTryNext = true;
		}
		
		return result;
	}
	
	private static long GetSum(long number)
	{
		long sum = 0;
		while (number > 0)
		{
			sum += number % 10;
			number /= 10;
		}
		return sum;
	}
	
	private static long GetSum(List<Long> elements)
	{
		if ((elements == null) ||
				(elements.size() <= 1))
			return -1;
		
		long sum = 0;
		for (long i : elements)
			sum += GetSum(i);
		
		return sum;
	}
	
	private static boolean IsSmith(long number)
	{
		if (number <= 3)
			return false;
		
		List<Long> elements = GetAllPrimeElements(number);
		
		long numberSum = GetSum(number);
		long elementsSum = GetSum(elements);
		
		return (numberSum == elementsSum);
	}
	
	private static void Handle(long n)
	{
		long number = n + 1;
		while (!IsSmith(number))
			++number;
		System.out.println(number);
	}
	
	public static void main(String[] args)
	{
		Scanner inScanner = new Scanner(System.in);
		long cnt = inScanner.nextLong();
		for (int i = 1; i <= cnt; ++i)
		{
			long n = inScanner.nextLong();
			if (n <= 3L)
				System.out.println(4);
			else
				Handle(n);
		}
	}

}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:23218次
    • 积分:749
    • 等级:
    • 排名:千里之外
    • 原创:55篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条
    文章分类