Consecutive Prime Sum Program in Java

The sum of consecutive prime numbers refers to the total obtained by adding up a series of prime numbers that follow each other in sequence.

To find consecutive prime numbers that sum up to a given value in Java, we can use a sliding window approach. Some prime numbers can be expressed as a sum of other consecutive prime numbers.

For example

  • 5 = 2 + 3,
  • 17 = 2 + 3 + 5 + 7,
  • 41 = 2 + 3 + 5 + 7 + 11 + 13.
    The task is to find out how many prime numbers that satisfy this property are present in the range 3 to N subject to a constraint that summation should always start with number 2.

Input: First line contains a number N.

Output: Print the total number of all such prime numbers which are less or equal to N.

The time complexity of the code is O(n2 * b + k).

The actual time complexity may vary depending on the values of n and b.

ConsecutiveSum.java

Output:

Enter no
10
4

Time complexity: O(sqrt(N))

Space complexity: O(1)

Let's see another approach for the same.

ConsecutivePrimeSum.java

Output:

50
3

Another solution:

Assume N = (x+1)+(x+2)+...+(x+k), where x >= 0, k >= 1.

We have 2N = k(2x+k+1), which has two factors, k and 2x+k+1, one of which is odd number and another is even. So, the question is how many ways to factor 2N into one even and one odd number.

Assume 2N = 2^t * M, where M is odd. If we factor M = a * b, then multiply 2^t to one of them will yield the even number. So the question now becomes how many ways to factor the odd part of N.

If N = 3*3*3*5*5, how many ways to factor N into two numbers?

For one number, we can pick 0 to 3 3s, and 0 to 2 5s, so we have 4 * 3 = 12 options.

Here we can see the answer is multiplication of 1 + {count of a factor}.

But what if there is a factor greater than sqrt(N)? In this case, it has to be a prime number and there will be only one of it. So, if eventually N > 1, we multiply 2 to answer.

ConsecutivePrimeSum.java

Output:

6

Time complexity: O(sqrt(N)

Space complexity: O(1)






Latest Courses