To make programs we will have to do conditions and loops. Here are a couple of typical examples.
for i in range(6):
print i
count=1
while count < 7 :
print count
count = count + 1
count=1
while count < 10 :
if count.is_square():
print count
count = count + 1
The proper indentation is important when you define a function.
for i in range(20):
n = i+1;
if n.is_prime():
print n, "is prime"
else:
print n, "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.
3.divides(12), 3.divides(10)
a = 3
a.prime_factors()
gcd(10,4)
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).
g,u,v = xgcd(10,4); g; u; v
Test that it is correct.
g == u*10 +v*4
It can even do this in more general rings.
P.<x> = PolynomialRing(ZZ)
(x+1).divides(x^2 - 1)
But lets just play with integers for now. Some more useful functions are.
factor(376824)
divisors(376824)
def myDivide(A,B):
q = 0
r = A
while r > B :
q = q + 1;
r = r - B;
return(q,r)
myDivide(27,4)