Count prime numbers that can be expressed as sum of consecutive prime numbers | Java program for the above approach ; Function to check if a number is prime or not ; Base Case ; Iterate till [ 5 , Math . sqrt ( N ) ] to detect primality of numbers ; If N is divisible by i or i + 2 ; Return 1 if N is prime ; Function to count the prime numbers which can be expressed as sum of consecutive prime numbers ; Initialize count as 0 ; Stores prime numbers ; If i is prime ; Initialize the sum ; Find all required primes upto N ; Add it to the sum ; Return the final count ; Driver Code ; Given number N ; Function Call
import java . util . * ; class GFG { static int isprm ( int n ) { if ( n <= 1 ) return 0 ; if ( n <= 3 ) return 1 ; if ( n % 2 == 0 n % 3 == 0 ) return 0 ; for ( int i = 5 ; i * i <= n ; i = i + 6 ) { if ( n % i == 0 || n % ( i + 2 ) == 0 ) return 0 ; } return 1 ; } static int countprime ( int n ) { int count = 0 ; Vector < Integer > primevector = new Vector < > ( ) ; for ( int i = 2 ; i <= n ; i ++ ) { if ( isprm ( i ) == 1 ) { primevector . add ( i ) ; } } int sum = primevector . elementAt ( 0 ) ; for ( int i = 1 ; i < primevector . size ( ) ; i ++ ) { sum += primevector . elementAt ( i ) ; if ( sum > n ) break ; if ( isprm ( sum ) == 1 ) { count ++ ; } } return count ; } public static void main ( String [ ] args ) { int N = 45 ; System . out . print ( countprime ( N ) ) ; } }