Montfrooij Posted March 13, 2012 Posted March 13, 2012 (edited) After a search on this forum AND the help files I did not find any satisfying functions to calculate the CGD (Common Greatest Divisor) for more than 2 numbers. Here is an example of my script. expandcollapse popup;Example data, enter your nr's in this array dim $nr[4] ;In this example just 4 nr's are entered, so therefor the [4] $nr[0] = 44 $nr[1] = 33 $nr[2] = 22 $nr[3] = 11 _cgdMultiple($nr) ;Call the multiple function Func _cgdMultiple($aNr) ;Function to call _cgd multiple times and return the cgd of all nr's in the $aNr array supplied For $i = 1 to ubound($aNr) - 1 ;loop through all nr's, the -1 is because we start with [0] but dim until [3] ;First time if $i = 1 Then $cgd = _cgd($aNr[$i-1],$aNr[$i]) MsgBox(0,$i,$aNr[$i-1] & "-" & $aNr[$i] & "-" & $cgd) ;Just to show what is happening Else ;Next time $cgdprev = $cgd ;Just to see what is happening, can be removed, but than the next line needs to be _cgd($cgd,$aNr[$i]) $cgd = _cgd($cgdprev,$aNr[$i]) MsgBox(0,$i,$cgdprev & "-" & $aNr[$i] & "-" & $cgd) ;Just to show what is happening EndIf Next MsgBox(0,"Result","cgd = " & $cgd) EndFunc ;===> _cgdMultiple Func _cgd($n, $m) ;Function to return the cgd of two nr's if $n > 0 and $m > 0 and StringIsInt($n) and StringIsInt($m) Then ;Check for valid input if ($n < $m) Then ;Make sure $n is bigger than $m $z = $n $n = $m $m = $z EndIf $r = 1 while $r <> 0 ;Subtract the floor of $n/m from $n to get the cgd $q = Floor($n/$m) $r = $n - ($m*$q) $n = $m $m = $r WEnd Else $n = 0 ;Not possible EndIf return $n EndFunc ;===> _cgd That's all. Comments / additions / corrections are welcome. BR, Peter Edited March 21, 2012 by Montfrooij
Montfrooij Posted March 21, 2012 Author Posted March 21, 2012 Thanks, edited the mixup. English is still hard to write.... Your function is a bit shorter, I will still need to verify that $a > $b so only the while is affected. I actually ended up not using the script, so when there is time left I will implement your version.
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now