Minimum possible final health of the last monster in a game | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int gcd ( int a , int b ) { if ( a == 0 ) return b ; return gcd ( b % a , a ) ; } 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 ; } int main ( ) { int health [ ] = { 4 , 6 , 8 , 12 } ; int n = sizeof ( health ) / sizeof ( health [ 0 ] ) ; cout << solve ( health , n ) ; return 0 ; }