Friday 29 July 2016

Problem : Consecutive Prime Sum Some prime numbers can be expressed as Sum of other consecutive prime numbers. For example 5 = 2 + 3 17 = 2 + 3 + 5 + 7 41 = 2 + 3 + 5 + 7 + 11 + 13 Your task is to find out how many prime numbers which satisfy this property are present in the range 3 to N subject to a constraint that summation should always start with number 2. Write code to find out number of prime numbers that satisfy the above mentioned property in a given range.

import java.util.*; class Prime{ public static void main(String []args) { int count=0,p=2,i; Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int a[]=new int[n+1]; for(i=0;i<=n;i++) { a[i]=i; } for(p=2;p*p<=n;p++) { if(a[p]!=0) { for(i=p*2;i<=n;i+=p) { a[i]=0; } int sum=5; for(i=5;i<=n+2;i=i+2){ if((a[i]!=0 && a[i]==sum)||a[i]==-1) count=count+1; if (a[i] != 0 || a[i] == -1) sum=sum+i; if(a[sum]!=0) a[sum]=-1; } } } System.out.print(count); } }

No comments:

Post a Comment