Minimum possible final health of the last monster in a game | Java implementation of the approach ; Function to return the gcd of two numbers ; Function to return the minimum possible health for the monster ; gcd of first and second element ; gcd for all subsequent elements ; Driver code
import java . util . * ; class GFG { static int gcd ( int a , int b ) { if ( a == 0 ) return b ; return gcd ( b % a , a ) ; } static int solve ( int health [ ] , int n ) { int currentgcd = gcd ( health [ 0 ] , health [ 1 ] ) ; for ( int i = 2 ; i < n ; ++ i ) { currentgcd = gcd ( currentgcd , health [ i ] ) ; } return currentgcd ; } public static void main ( String args [ ] ) { int health [ ] = { 4 , 6 , 8 , 12 } ; int n = health . length ; System . out . println ( solve ( health , n ) ) ; } }