The sum of primes#1352

The sum of primes (Editorial)

Iterate through the sequence of prime numbers (2, 3, 5, 7, ...) and accumulate their sum. As soon as this sum becomes divisible by without a remainder, print the number of terms used.

Example

The sum of the first five prime numbers 2 + 3 + 5 + 7 + 11 equals and is divisible by .

Algorithm implementation

The function prime returns if the number is prime.

int prime(int n)
{
  if (n == 2) return 1;
  if (n % 2 == 0) return 0;
  for(int i = 3; i <= sqrt(n); i += 2)
    if(n % i == 0) return 0;
  return 1;
}

The main part of the program. Read the value of .

scanf("%d",&k);

The variable stores the sum of prime numbers, and the variable stores their count.

s = c = 0;

Iterate over numbers starting from . If the current number is prime, add it to and increase . As soon as the sum becomes divisible by , the loop stops.

for(i = 2;; i++)
{
  if (prime(i))
  {
    s += i; c++;
    if (s % k == 0) break;
  }
}

Print the minimum number of initial prime numbers whose sum is divisible by .

printf("%d\n",c);

Java implementation

import java.util.*;

public class Main
{
  public static boolean prime(int n)
  {
    if (n == 2) return true;
    if (n % 2 == 0) return false;
    for(int i = 3; i <= Math.sqrt(n); i += 2)
      if(n % i == 0) return false;
    return true;
  }

  public static void main(String[] args)
  {
    Scanner con = new Scanner(System.in);
    int k = con.nextInt();
    int s = 0, c = 0;
    for(int i = 2;; i++)
    {
      if (prime(i))
      {
        s += i; c++;
        if (s % k == 0) break;
      }
    }
    System.out.println(c);
    con.close();
  }
}

Python implementation

The function prime returns if the number is prime.

def prime(n):
  if n == 2: return True
  if n % 2 == 0: return False
  for i in range(3, int(math.sqrt(n))+1, 2):
    if n % i == 0: return False
  return True

The main part of the program. Read the value of .

k = int(input())

The variable stores the sum of prime numbers, and the variable stores their count.

s = c = 0
i = 2

Iterate over numbers starting from . If the current number is prime, add it to and increase . As soon as the sum becomes divisible by , the loop stops.

while True:
  if (prime(i)):
    s += i
    c += 1
    if s % k == 0: break
  i += 1

Print the minimum number of initial prime numbers whose sum is divisible by .

print(c);