To make programs we will have to do conditions and loops. Here are a couple of typical examples.

In [1]:
for i in range(6):
   print i
0
1
2
3
4
5
In [2]:
count=1
while count < 7 :
    print count
    count = count + 1
1
2
3
4
5
6
In [3]:
count=1
while count < 10 :
    if count.is_square():
      print count
    count = count + 1
1
4
9

Important:

The proper indentation is important when you define a function.

In [4]:
for i in range(20):
    n = i+1;
    if n.is_prime(): 
        print n, "is prime"
    else: 
        print n, "is composite"
1 is composite
2 is prime
3 is prime
4 is composite
5 is prime
6 is composite
7 is prime
8 is composite
9 is composite
10 is composite
11 is prime
12 is composite
13 is prime
14 is composite
15 is composite
16 is composite
17 is prime
18 is composite
19 is prime
20 is composite

Section 1.2  Divisibility and GCDs.

Sage can quickly decide for us if a number divides another, or find the GCD of two numbers.

In [5]:
3.divides(12), 3.divides(10)
Out[5]:
(True, False)
In [6]:
a = 3
In [7]:
a.prime_factors()
Out[7]:
[3]
In [8]:
gcd(10,4)
Out[8]:
2

We can even do the Extended Euclidean Algorithm to compute the coefficients u and v of a and b in representing the g = gcd(a,b).

In [9]:
g,u,v = xgcd(10,4); g; u; v
Out[9]:
-2

Test that it is correct.

In [10]:
g == u*10 +v*4
Out[10]:
True

It can even do this in more general rings.

In [11]:
P.<x> = PolynomialRing(ZZ)
In [12]:
(x+1).divides(x^2 - 1)
Out[12]:
True

But lets just play with integers for now. Some more useful functions are.

In [13]:
factor(376824)
Out[13]:
2^3 * 3 * 7 * 2243
In [14]:
divisors(376824)
Out[14]:
[1,
 2,
 3,
 4,
 6,
 7,
 8,
 12,
 14,
 21,
 24,
 28,
 42,
 56,
 84,
 168,
 2243,
 4486,
 6729,
 8972,
 13458,
 15701,
 17944,
 26916,
 31402,
 47103,
 53832,
 62804,
 94206,
 125608,
 188412,
 376824]
In [15]:
def myDivide(A,B):
    q = 0
    r = A
    while r > B :
        q = q + 1;
        r = r - B;
    return(q,r)
In [17]:
myDivide(27,4)
Out[17]:
(6, 3)