home *** CD-ROM | disk | FTP | other *** search
/ The Unsorted BBS Collection / thegreatunsorted.tar / thegreatunsorted / programming / misc_programming / batnmore.z!p / GCD-LCM.BTM < prev    next >
Text File  |  1992-11-15  |  2KB  |  83 lines

  1. *REM This batch file is Freeware, free to use and redistribute unmodified *
  2. *REM Jouni Miettunen * jon@stekt.oulu.fi * Oulu * Finland * Europe * 1992 *
  3.  
  4. REM Greatest Common Divisor and Least Common Multiplier
  5. REM Timestamp 15-Nov-1992
  6.  
  7. REM Note: EVAL can calculate 16 digit integers, IF/IFF compare 9 digit integer.
  8. REM Note: calculating LCM *can* cause overflow (multiplication).
  9.  
  10. setlocal^break on^unalias *^if %#==0 .or. "%1"=="-?" goto info^set dec=100
  11.  
  12. REM Did the user give a legal decimal string? Nothing but numbers?
  13.  
  14. :input
  15. iff "%1"=="%@int[%1]" then^set %dec=%1^set dec=%@eval[%dec+1]
  16. else^echo Error: "%1" NaN (Not a Number).^goto next^endiff
  17.  
  18. REM At the moment we can calculate max 16 digit numbers.
  19. REM Note: hard to check for overflow without overflow, so I didn't even try.
  20. REM It's fast this way and you'll notice, when errors occur...
  21.  
  22. iff %@len[%1] gt 16 then
  23. echo Error: "%1" too long for me.^unset %dec^set dec=%@eval[%dec-1]^endiff
  24.  
  25. REM Is there more?
  26.  
  27. :next
  28. shift^if "%1" != "" goto input
  29.  
  30. REM Do we have something to calculate?
  31.  
  32. if "%100"=="" goto info^set dec=100
  33. if "%[%dec]"=="" set %dec=1^set gcd=%[%dec]
  34. echos Calculating Greatest Common Divisor...
  35.  
  36. REM Main loop for GCD calculation
  37.  
  38. :gcd
  39. set dec=%@eval[%dec+1]^iff "%[%dec]" != "" then
  40.     set a=%gcd^set b=%[%dec]^gosub gcdloop
  41.     goto gcd
  42. endiff
  43. screen %_row 0 Greatest Common Divisor is %gcdn
  44. echos Calculating Least Common Multiplier...
  45. set dec=99^set lcm=1^goto lcm
  46.  
  47. REM GCD for two numbers
  48.  
  49. :gcdloop
  50. REM if %a is less than %b then do...
  51. iff %@ascii[%@eval[%a-%b]]==45 then^set c=%a^set a=%b^set b=%c^endiff
  52. set a=%@eval[%a %% %b]^if %a != 0 goto gcdloop^set gcd=%b^return
  53.  
  54. REM Setup for LCM calculation
  55.  
  56. :lcm
  57. set dec=%@eval[%dec+1]^iff "%[%dec]" != "" then
  58.     set lcm=%@eval[%lcm * %[%dec]]
  59.     goto lcm
  60. endiff
  61. set dec=100
  62.  
  63. REM Calculate LCM
  64.  
  65. :lcmloop
  66. set dec=%@eval[%dec+1]^iff "%[%dec]" != "" then
  67.     set lcm=%@eval[%lcm / %gcd]
  68.     goto lcmloop
  69. endiff
  70. screen %_row 0 Least Common Multiplier is %lcmn
  71. goto end
  72.  
  73. :info
  74. echo Usage: %@lower[%@name[%0]] [number ...]
  75. text
  76.  
  77. Calculate Greatest Common Divisor and Least Common Multiplier.
  78. Numbers have to be positive integers with max 16 digits in each.
  79. endtext
  80.  
  81. :end
  82. break off^quit
  83.