Code archives/Algorithms/mathematical algorithms

This code has been declared by its author to be Public Domain code.

Download source code

mathematical algorithms by 5t@nKy
(Posted 21 years ago)
some mathematical algorithms
Here are some of my collections:

this is the 'heron-algorithm' with which you can get the square root from 'n'

Function Sqr#(n#)
   x0#=1
   repeat
      check#=0.5*(x0#+n#/x0#)
      x0#=x1#
   until check#=x0#
   return x0#
end function

this function is to get the greatest common divisor:

Function gcd(A,B)
   While B > 0
      R=A mod B
      A=B
      B=R
   Wend
   Return A
End Function

this function is to get the least common denominator and based on the gcd function

Function lcd(A,B)
   C=(A*B)/gcd(A,B)
   Return C
End Function

to get the factorial of a number you can use this

Function fac(n)
   check=1
   For i=1 To n
      check=check*1
   Next
   Return check
Emd Function

this function is to get the binomial coefficient, this is to get the number of Pascal's triangle (n choose k)

Function nCk(n,k)
   Return Fac(n)/(Fac(k)*Fac(n-k))
End Function

so that's it!

I hope it's useful and sorry for my bad english^^

Comments

Matty
(Posted 21 years ago)
Without actually testing it myself I would make the comment that with Heron's Algorithm it would be better to finish the repeat..until loop when abs(check-xo)<some small tolerance value as otherwise it could loop indefinitely for some values.

Floyd
(Posted 21 years ago)
Sometimes you have to be careful with integer arithmetic as well.
With large numbers A*B can 'overflow'. Here is an example of the problem and a corrected lcd().
big1 = 100000
big2 = 150000

Print gcd(big1, big2)
Print lcd(big1, big2)
Print lcd2(big1, big2)

WaitKey

Function gcd(A,B)
   While B > 0
      R=A Mod B
      A=B
      B=R
   Wend
   Return A
End Function

Function lcd(A,B)
   C=(A*B)/gcd(A,B)
   Return C
End Function

Function lcd2(A,B)
   Return A * ( B / gcd(A,B) )
End Function


TAS
(Posted 18 years ago)
Function fac(n)
check=1
For i=1 To n
check=check*1
Next
Return check
Emd Function

;should be
Function fac(n)
check=1
For i=1 To n
check=check*n
Next
Return check
End Function

degac
(Posted 18 years ago)
I think there's a type-error in the FAC function
Function fac(n)
   check=1
   For i=1 To n
      check=check*i
   Next
   Return check
End Function

Print "4! = "+fac(4)
Print "3! = "+fac(3)
Print "-1! = "+fac(-1)
Print "-4! = "+fac(-4)

Print "0! = "+fac(0)


Warpy
(Posted 18 years ago)
That works for me... factorial isn't really defined for negative numbers.

Code Archives Forum