Problem 51

問題描述:

 

 

By replacing the 1st digit of *3, it turns out that six of the nine possible values: 13, 23, 43, 53, 73, and 83, are all prime.

By replacing the 3rd and 4th digits of 56**3 with the same digit, this 5-digit number is the first example having seven primes among the ten generated numbers, yielding the family: 56003, 56113, 56333, 56443, 56663, 56773, and 56993. Consequently 56003, being the first member of this family, is the smallest prime with this property.

Find the smallest prime which, by replacing part of the number (not necessarily adjacent digits) with the same digit, is part of an eight prime value family.

 

 

 

解決問題:

 

 

 

package projecteuler;

import java.util.Arrays;

public class Problem51 {

	public static boolean[] prime = new boolean[2000000];

	public static boolean IsPrime(long number) {

		for (int i = 2; i * i <= number; i++) {
			if (number % i == 0)
				return false;
		}
		return true;
	}

	public static void main(String[] args) {
		Arrays.fill(prime, false);
		for (int i = 1; i < prime.length; i++) {
			if (IsPrime(i)) {
				prime[i] = true;
			}
		}
		boolean ok = true;
		for (int i = 10000; i < prime.length && ok; i++) {
			// int i = 56003;
			if (prime[i]) {
				int begin = 0;
				for (begin = 0; begin < 3; begin++) {
					int number = i;
					int count = 0;
					int count_cur = 0;
					int add = 0;
					number = number / 10;
					while (number != 0) {
						int cur = number % 10;
						if (cur == begin) {
							add = add * 10 + 1;
							count_cur++;
						} else {
							add *= 10;
						}
						number = number / 10;
					}
					if (count_cur > 1) {
						add *= 10;
						// System.out.println("Add:"+add);
						int end = 9 - begin;
						int total = 1;
						int tmp = i;
						for (int j = 0; j < end; j++) {
							tmp += add;
							// System.out.println("Tmp:"+tmp);
							if (prime[tmp]) {
								total++;
							}
						}
						if (total == 8) {
							System.out.println("Number:" + i);
							System.out.println("Add:" + add);
							ok = false;
							break;
						}
					}
				}
			}
		}
	}
}
 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章