Minimize the cost to split a number | check if a number is prime or not ; run a loop upto square root of x ; Function to return the minimized cost ; If n is prime ; If n is odd and can be split into ( prime + 2 ) then cost will be 1 + 1 = 2 ; Every non - prime even number can be expressed as the sum of two primes ; n is odd so n can be split into ( 3 + even ) further even part can be split into ( prime + prime ) ( 3 + prime + prime ) will cost 3 ; Driver code
function isPrime ( x ) { for ( let i = 2 ; i * i <= x ; i ++ ) { if ( x % i == 0 ) return 0 ; } return 1 ; } function minimumCost ( n ) { if ( isPrime ( n ) ) return 1 ; if ( n % 2 == 1 && isPrime ( n - 2 ) ) return 2 ; if ( n % 2 == 0 ) return 2 ; return 3 ; } let n = 6 ; document . write ( minimumCost ( n ) ) ;