110706 Smith Numbers


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);
		}
	}

}


阅读更多
文章标签: 编程
个人分类: 算法练习
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

110706 Smith Numbers

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭