You are viewing a single comment's thread. Return to all comments →
java code
import java.util.Scanner;
public class Solution {
public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int T = scanner.nextInt(); for (int t = 0; t < T; t++) { long N = scanner.nextLong(); findLongestConsecutivePrimeSum(N); } scanner.close(); } private static void findLongestConsecutivePrimeSum(long N) { boolean[] isPrime = sieveOfEratosthenes(N); long resultPrime = 0; int maxLength = 0; for (int start = 2; start < N; start++) { long sum = 0; int length = 0; for (int current = start; current < N; current++) { if (isPrime[current]) { sum += current; length++; if (sum > N) { break; } if (isPrime[(int) sum] && length > maxLength) { maxLength = length; resultPrime = sum; } } } } System.out.println(resultPrime + " " + maxLength); } private static boolean[] sieveOfEratosthenes(long limit) { boolean[] isPrime = new boolean[(int) (limit + 1)]; for (int i = 2; i <= limit; i++) { isPrime[i] = true; } for (int i = 2; i * i <= limit; i++) { if (isPrime[i]) { for (int j = i * i; j <= limit; j += i) { isPrime[j] = false; } } } return isPrime; }
}
Seems like cookies are disabled on this browser, please enable them to open this website
Project Euler #50: Consecutive prime sum
You are viewing a single comment's thread. Return to all comments →
java code
import java.util.Scanner;
public class Solution {
}