Thursday, 20 March 2014

Finding Factors with Smalltalk

I've been looking for ways to cover the primary maths curriculum with real world examples or visual representations. Some of the curriculum is easy (for angles and gradients we can cycle up some hills) but some is a bit harder.

What about factors and prime numbers? While I have a think about the real world example of this I thought I'd put together a visual created with a little Smalltalk program to explore further.

You can see the results here... circles represent factors, so 10 has factors of 2 and 5, and each factor has a white stripe up to the number, so the whiter the background the more factors. This makes the primes easy to spot, e.g. 3, 5, 7, 11...


Some interesting questions:


  1. Why do some numbers have more factors than others? 
  2. Are there any repeating patterns in the dots?
  3. Do we see any of the numbers with a high number of factor (e.g. 12, 24, 36) in real life?
--

Here's the code:

First add the new class...

Object subclass: #FactorGrid
instanceVariableNames: 'rect max spacing'
classVariableNames: ''
poolDictionaries: ''
category: 'GeekClub'

And then the methods...

drawXLabels
| t |

1 to: max do: [ :i | 
t := TextMorph new.
t newContents: i asStringWithCommas.
t position: (i * spacing)@25.
rect addMorph: t.
]

highlightNumber: i forFactor: f
| r |

r := RectangleMorph new.
r position: ((i * spacing )- 4)@25.
r extent: (spacing * 0.9)@((f * 25) - 5).
r color: ((Color white) alpha: 0.2).
r borderWidth: 0.
rect addMorph: r.

initialize
max := 40.
spacing := 24.

rect := RectangleMorph new openInWorld.
rect color: (Color r: 0.972 g: 0.878 b: 0.819).
rect extent: 1000@500.
rect position: 0@20.
rect borderWidth: 1.

self drawXLabels.

plot: aNumber
| c t |

t := TextMorph new.
t newContents: aNumber asStringWithCommas.
t position: 5@(aNumber * 25).
rect addMorph: t.

1 to: max do: [ :i | 
(i \\ aNumber) isZero ifTrue: [ 
c := CircleMorph new.
c position: ((i * spacing) + 3)@(aNumber * 25).
c extent: 10@10.
(i = aNumber) ifTrue: [
c color: Color red.
]
ifFalse: [
self highlightNumber: i forFactor: aNumber.
].
rect addMorph: c.
]
]

plot: i to: j 
i to: j do: [ :a | self plot: a ].

Now you can create the drawing... open a new Workspace and run the following (one line at a time):

g := FactorGrid new.
g plot: 2.
g plot: 3.
g plot: 4 to: 20.


No comments:

Post a Comment