This is a read-only archive of the old Scratch 1.x Forums.
Try searching the current Scratch discussion forums.

#1 2012-03-16 16:44:34

hpwise
New Scratcher
Registered: 2012-02-01
Posts: 1

Greatest common factor/ least common multiple?

How could i write a script that finds the greatest common factor of 2 numbers?

Also, how could i write a script that finds the least common multiple of 2 numbers?

Offline

 

#2 2012-03-16 17:55:27

turkey3
Scratcher
Registered: 2011-12-04
Posts: 500+

Re: Greatest common factor/ least common multiple?

I dont even think its possible, but I know how to find a multiple, but not the least common one. You just multiply the 2 numbers together.

Offline

 

#3 2012-04-02 22:51:23

aryabtsev
Scratcher
Registered: 2012-02-05
Posts: 81

Re: Greatest common factor/ least common multiple?

I looked this formula up Wikipedia and tested it, it should work: (this is GCF)

repeat until <((a) mod (b)) = (0)>
   set [temp v] to (b)
   set [b v] to ((a) mod (b))
   set [a v] to (temp)
end
set [result v] to (b)
Hope it's helpful, I'll look up least common multiple in a second.


http://i.imgur.com/NX7AO.jpg

Offline

 

#4 2012-04-02 22:56:44

aryabtsev
Scratcher
Registered: 2012-02-05
Posts: 81

Re: Greatest common factor/ least common multiple?

I think LCM is:
abs(a*b)/GCF(a,b)
where GCF is greatest common factor


http://i.imgur.com/NX7AO.jpg

Offline

 

#5 2012-04-02 23:16:26

MoreGamesNow
Scratcher
Registered: 2009-10-12
Posts: 1000+

Re: Greatest common factor/ least common multiple?

LCM

set [a v] to (number 1)
set [b v] to (number 2)
set [guess v] to (a) // if a is the bigger number, it is more efficient
repeat until <((a) mod (b)) = [0]>
change [guess v] by (a)
end
GCF
set [a v] to (number 1)
set [b v] to (number 2)
set [guess v] to (a)
repeat until <<((b) mod (guess)) = [0]> and <((a) mod (guess)) = [0]>>
change [guess v] by (-1)
end
Edit: I'm sure there is a more efficient method for GCF, I'm just too tired to think right now (it would help if you had a list of primes though)

Last edited by MoreGamesNow (2012-04-02 23:16:58)


http://images2.layoutsparks.com/1/218929/rubiks-cube-animated-rotating.gif
"Cogito ergo sum" --  I think, therefore I am

Offline

 

#6 2012-04-03 16:32:04

Ratty1967UK
Scratcher
Registered: 2007-05-16
Posts: 88

Re: Greatest common factor/ least common multiple?

aryabtsev was spot on! here's the two algorithms combined...

http://scratch.mit.edu/projects/Ratty1967UK/2443899

smile

Offline

 

Board footer