Project Euler NO32

如果一個n位數使用了1到n中每個數字且只使用了一次,我們稱其爲pandigital。例如,15234這個五位數,是1到5pandigital的。

7254是一個不尋常的數,因爲:39 × 186 = 7254這個算式的乘數,被乘數和乘積組成了一個1到9的pandigital組合。
找出所有能夠組合成1到9pandigital的乘法算式中乘積的和。

提示: 有的乘積數字能夠被多個乘法算式得到,所以在計算時要記得只計算它們一次。



分析:

a * b = c
1   2   
1   3 
1   4   4
2位 * 2 位  最多 4 位  (去掉)
2   3   4
3   3   3(去掉)

所以
1 < a < 99;
12 < b < 9999;


import java.util.ArrayList;
import java.util.List;


public class Problem32
{
	public static void main(String[] args)
	{
		long start = System.currentTimeMillis();
		System.out.print("answer:  ");
		
		howmany();
		
		long end = System.currentTimeMillis();
		System.out.print("time:  ");
		System.out.println(end - start);
	}
	
	static List<Integer> all = new ArrayList<>();
	static void howmany()
	{
		int sum = 0;
		for (int a = 1; a < 99; a++)
		{
			for(int b = 12; b < 9999; b++)
			{
				int c = a * b;
				if ((c + "").length() != 9 - (a + "").length() - (b + "").length() )
				{
					continue;
				}
				
				if (check(a + "" + b + c))
				{
					if (ishad(c))
					{
						sum += c;
					}
				}
			}
		}
		System.out.println(sum);
	}
	
	static boolean ishad(int n)
	{
		for (int i = 0; i < all.size(); i++)
		{
			if (n == all.get(i))
			{
				return false;
			}
		}
		
		all.add(n);
		return true;
	}
	
	static boolean check(String str)
	{
		char ch[] = str.toCharArray();
		for (int i = 0; i < str.length(); i++)
		{
			if (ch[i] == '0')
			{
				return false;
			}
			for (int j = i + 1; j < str.length(); j++)
			{
				if (ch[j] == '0')
				{
					return false;
				}
				
				if (ch[i] == ch[j])
				{
					return false;
				}
			}
		}
		
		return true;
	}
	
}

answer:  45228
time:  526
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章