| Modulus
in Actionscript and Javascript
Why Modulus?
I was teaching a class in Intermediate
to Advanced Actionscript, and for some reason the idea
of modulus came up. We were importing a list of thumbnails
from XML, and what we wanted to do was display them
in rows of 3.
Modulus is the remainder after two
numbers are divided. The mathematical symbol for modulus
(at least in Javascript, PHP, and Actionscript) is the
percentage sign (%).
eg.
4%3=1
22%5=2
20%4=0
Modulus is just about the remainder.
If you want to know if a number is even or odd, modulus
it by 2 and if there is a remainder the number is
odd.
Or, in Actionscript:
n=n%2;
if(n==0){
trace("n is even");
}
Prime Number
Identifying
I was thinking about making a loop
to check whether a number was prime. You're probably
thinking of one right now, using modulus.
Let's start with a number like 337.
n=337;
x=n%2;
if(x==0){
trace("n is not prime");
// I would stop the loop here
}
x=n%3;
if(x==0){
trace("n is not prime");
// I would stop the loop here
}
etc.
|
I would keep increasing the value
of the number after the modulus sign until I have reached
half of 337 (anything afterward is redundant).
What you're looking for is to prove
that 337 is _not_ prime by getting modulus = 0 at least
once.
I would put that all in a Javascript
loop like so:
i= 337;
halfI= Math.round(i/2);
for(x=2; x<halfI; x++){
iMod=halfI%x;
if(iMod==0){
document.write(i + " is
not prime");
}
}
Using the same logic I could look
through a number and count and display all the factors
of that number.
How does this apply to my Actionscript
example at the top of the previous column? Let's say
I have 10 jpeg thumbnails from a dynamic list, maybe
my favourite CDs of 2003. My design requires thumbnails
to be in 3 columns. And let's assume my list of albums
is already in the form of an array.
topCDs[0]="Geoff Berner, We Shall
Not Flag or Fail";
topCDs[1]="Bright Eyes, Lifted"; // etc.
// loop through array and display the albums
// I'll do this in Javascript, cuz it's easier to demo
x=topCDs.length; // count number of items in list
for (i=0;i<x;i++){ // loop through list starting
at 0
document.write("<img src='" + topCDs[i]
+ "'>");
iMod = i%3; // because there are 3 columns
if(iMod==2){ // because iMod values are
0,1,2
document.write("<br>");
}
}
This isn't a great example, cuz the
items in the array are album _names_, not jpeg locations,
but you get the idea.
MORE
TUTORIALS
|