Welcome, guest | Sign In | My Account | Store | Cart

finds the least common multiple and the greatest common factor of three numbers. i wrote it a while ago for school.

Python, 56 lines
 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 ################################################################ # program name: least common multiple and gratest common facter # author: max baseman # email: dos.fool@gmail.com # date: 01/16/07 # description: a program to find the LCM # and gcf of three given numbers # # ################################################################ print print print"enter three numbers to get the LCM and gcf of" num1=input("number 1 >") num2=input("number 2 >") num3=input("number 3 >") #find the lowest number if num1 < num2 and num1 < num3: low = num1 elif num2 < num1 and num2< num3: low = num2 elif num3 < num1 and num3 < num2: low = num3 # find the highest number if num1 > num2 and num1 > num3: high=num1 elif num2 > num1 and num2 > num3: high=num2 elif num3 > num1 and num3 > num2: high=num3 # start at the largest number because the LCM cant be smaller then the highist number number=high #loop till finds the lowest number while 1: numtest=number+.0 if numtest/num1 == number/num1: if numtest/num2 == number/num2: if numtest/num3 == number/num3: break number=number+1 LCM=number #apply number to LCM so that i can keep useing number for GCF number=2 while number <= low: numtest=number+.0 if num1/numtest == num1/number: if num2/numtest == num2/number: if num3/numtest == num3/number: break number=number+1 else: number=1 GCF=number print print print"the LCM was",LCM,"and the GCF was",GCF

this is a simple program that can be used for school purposes or just to shortin the time it takes to calculate by hand. Steven Bethard 14 years, 10 months ago

min(), max() or sorted(). This is ugly:

if num1 &gt; num2 and num1 &gt; num3:
low = num1
elif num2 &gt; num1 and num2 &gt; num3:
low = num2
elif num3 &gt; num1 and num3 &gt; num2:
low = num3
# find the highest number
if num1 &lt; num2 and num1 &lt; num3:
high=num1
elif num2 &lt; num1 and num2 &lt; num3:
high=num2
elif num3 &lt; num1 and num3 &lt; num2:
high=num3

Ouch! Try using min() and max():

low = min(num1, num2, num3)
high = max(num1, num2, num3)

Or maybe sorted():

low, mid, high = sorted([num1, num2, num3]) greg p 14 years, 6 months ago

Web Based Implementation. I made a web based GUI for a function like this calculating greatest common factor and least common multiple:

http://www.utilitymill.com/utility/GCF_and_LCM_Calculator

The code for it is listed here if you're curious: http://www.utilitymill.com/edit/GCF_and_LCM_Calculator Created by max baseman on Sat, 24 Mar 2007 (PSF)

Required Modules

• (none specified)