Consecutive prime sum
C#include<stdio.h>
#include<math.h>
int arr[100];
int isPrime(int n) {
if(n==2)
return 1;
if(n%2==0)
return 0;
for(int i=3;i<=sqrt(n);i=i+2) {
if(n%i==0)
return 0;
}
return 1;
}
void getAllPrimes(int n) {
int j=0;
for(int i=3;i<n;i=i+2) {
if(isPrime(i))
arr[j++]=i;
}
}
int search(int key){
int i=0;
for(i=0;i<100;i++){
if(key==arr[i])
return 1;
}
return 0;
}
int main(){
int n,s=0,i=1,count=1;
scanf("%d",&n);
getAllPrimes(n);
while(s<=n) {
s+=arr[i++];
if(search(s))
count++;
}
printf("%d",count);
return 0;
}
JAVA
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class ConsecutivePrimeSum {
static boolean isPrime(int n) {
if(n==2)
return true;
if(n%2==0)
return false;
for(int i=3;i<Math.sqrt(n);i=i+2) {
if(n%i==0)
return false;
}
return true;
}
static ArrayList getAllPrimes(int n) {
ArrayList<Integer> arr=new ArrayList<Integer>();
for(int i=3;i<n;i=i+2) {
if(isPrime(i))
arr.add(i);
}
return arr;
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
ArrayList<Integer> arr=getAllPrimes(n);
int s=0,i=0,count=0;
while(s<=n) {
s+=arr.get(i);
i++;
if(Collections.binarySearch(arr, s)>=0)
count++;
}
System.out.print(count);
}
}
PYTHON
def bin_search(arr, left, high, key):
mid = (left + high) // 2
if left > high:
return -1
if arr[mid] == key:
return mid
if arr[mid] > key:
return bin_search(arr, left, mid - 1, key)
if arr[mid] < key:
return bin_search(arr, mid + 1, high, key)
def isPrime(n):
if n==2:
return True
if n%2==0:
return False
for i in range(3,int(n**0.5)+1,2):
if n%i==0:
return False
return True
n=int(input())
primes=[]
for i in range(3,n+1,2):
if(isPrime(i)):
primes.append(i)
s=0
i=0
count=0
while s<=n:
s=s+primes[i]
i+=1
if bin_search(primes,0,len(primes)-1,s)!=-1:
count+=1
print(count)