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.
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.
Input Format:
First line contains a number N
First line contains a number N
Output Format:
Print the total number of all such prime numbers which are less than or equal to N.
Print the total number of all such prime numbers which are less than or equal to N.
SOLUTION IN JAVA
import java.util.*;
public class primesum {
public static void main(String []args){
Scanner sc=new Scanner(System.in);
int n=sc.nextInt(),i,k,sum,count;
for(i=3;i<=n;i++){
sum=0;count=0;
if(checkPrime(i)){
for(k=2;k<i;k++){
if(checkPrime(k)){
sum+=k;
count++;
if(sum==i){
System.out.println(count+"\t"+i);
break;
}
}
}
}
}}
public static boolean checkPrime(int i){
int j,count=0;
boolean bo;
int m=i/2;
for( j=2;j<i;j++){
if(i%j==0) {
count++;
break;
}
}
if(count>0)
{
bo=false;
}
else bo=true;
return bo;
}
}
INPUT: 20
public class primesum {
public static void main(String []args){
Scanner sc=new Scanner(System.in);
int n=sc.nextInt(),i,k,sum,count;
for(i=3;i<=n;i++){
sum=0;count=0;
if(checkPrime(i)){
for(k=2;k<i;k++){
if(checkPrime(k)){
sum+=k;
count++;
if(sum==i){
System.out.println(count+"\t"+i);
break;
}
}
}
}
}}
public static boolean checkPrime(int i){
int j,count=0;
boolean bo;
int m=i/2;
for( j=2;j<i;j++){
if(i%j==0) {
count++;
break;
}
}
if(count>0)
{
bo=false;
}
else bo=true;
return bo;
}
}
INPUT: 20
OUTPUT:
2 5
4 17
working efficiently.
ReplyDelete