Sage Demo Egham
system:sage

<h2>Some Calculus</h2>

{{{id=0|
2 + 3
///

5
}}}

{{{id=1|
x = var('x')
show(plot(sin(x^2), 0, pi))
///
}}}

{{{id=2|
a = integrate(sin(x^2),x); a
///

sqrt(pi)*((sqrt(2)*I + sqrt(2))*erf((sqrt(2)*I + sqrt(2))*x/2) + (sqrt(2)*I - sqrt(2))*erf((sqrt(2)*I - sqrt(2))*x/2))/8
}}}

{{{id=151|
show(a)
///

<html><div class="math">\frac{{\sqrt{ \pi } \left( {\left( {\sqrt{ 2 } i} + \sqrt{ 2 } \right) \text{erf} \left( \frac{{\left( {\sqrt{ 2 } i} + \sqrt{ 2 } \right) x}}{2} \right)} + {\left( {\sqrt{ 2 } i} - \sqrt{ 2 } \right) \text{erf} \left( \frac{{\left( {\sqrt{ 2 } i} - \sqrt{ 2 } \right) x}}{2} \right)} \right)}}{8}</div></html>
}}}

{{{id=3|
latex(a)
///

\frac{{\sqrt{ \pi } \left( {\left( {\sqrt{ 2 } i} + \sqrt{ 2 } \right) \text{erf} \left( \frac{{\left( {\sqrt{ 2 } i} + \sqrt{ 2 } \right) x}}{2} \right)} + {\left( {\sqrt{ 2 } i} - \sqrt{ 2 } \right) \text{erf} \left( \frac{{\left( {\sqrt{ 2 } i} - \sqrt{ 2 } \right) x}}{2} \right)} \right)}}{8}
}}}

{{{id=68|
var('a,b,c,X')
s = solve(a*X^2 + b*X + c == 0, X)
show(s[0])
///

<html><div class="math">X  =  \frac{-\left( \sqrt{ {b}^{2}  - {{4 a} c} } \right) - b}{{2 a}}</div></html>
}}}

{{{id=6|
reset('e')
x = var('x')
f   = sin(x)*e^(-x)
p   = plot(f,-1,5, thickness=2)
@interact
def _(order=(1..12), x0=input_box("0",label="x_0")):
  x0 = int(x0)
  dot = point((x0,f(x0)),pointsize=80,rgbcolor=(1,0,0))
  ft = f.taylor(x,x0,order)
  pt = plot(ft,-1, 5, color='green', thickness=2)
  html('$f(x)\;=\;%s$'%latex(f))
  html('$\hat{f}(x;%s)\;=\;%s+\mathcal{O}(x^{%s})$'%(x0,latex(ft),order+1))
  show(dot + p + pt, ymin = -.5, ymax = 1)
///

<html><!--notruncate--><div padding=6 id='div-interact-6'> <table width=800px height=20px bgcolor='#c5c5c5'
                 cellpadding=15><tr><td bgcolor='#f9f9f9' valign=top align=left><table><tr><td align=right><font color="black">order&nbsp;</font></td><td><table><tr><td>
    	<div id='slider-order-6' class='ui-slider-3' style='padding:0px;margin:0px;'><span class='ui-slider-handle'></span></div>
    	</td><td><font color='black' id='slider-order-6-lbl'></font></td></tr></table><script>(function(){ var values = ["1","2","3","4","5","6","7","8","9","10","11","12"]; setTimeout(function() {
    $('#slider-order-6').slider({
    	stepping: 1, minValue: 0, maxValue: 11, startValue: 0,
    	change: function () { var position = Math.ceil($('#slider-order-6').slider('value')); if(values!=null) $('#slider-order-6-lbl').text(values[position]); interact(6, "sage.server.notebook.interact.update(6, \"order\", 5, sage.server.notebook.interact.standard_b64decode(\""+encode64(position)+"\"), globals())"); },
    	slide: function() { if(values!=null) $('#slider-order-6-lbl').text(values[Math.ceil($('#slider-order-6').slider('value'))]); }
    });
    if(values != null) $('#slider-order-6-lbl').text(values[Math.ceil($('#slider-order-6').slider('value'))]);
    }, 1); })();</script></td></tr>
<tr><td align=right><font color="black">x_0&nbsp;</font></td><td><input type='text' value=''0'' size=80 onchange='interact(6, "sage.server.notebook.interact.update(6, \"x0\", 6, sage.server.notebook.interact.standard_b64decode(\""+encode64(this.value)+"\"), globals())")'></input></td></tr>
</table><div id='cell-interact-6'><?__SAGE__START>
        <table border=0 bgcolor='#white' width=100% height=100%>
        <tr><td bgcolor=white align=left valign=top><pre><?__SAGE__TEXT></pre></td></tr>
        <tr><td  align=left valign=top><?__SAGE__HTML></td></tr>
        </table><?__SAGE__END></div></td>
                 </tr></table></div>
                 </html>
}}}

<h2>Interactive 3D Plotting</h2>

{{{id=150|
# Mobius strip:
u,v = var("u,v")
p = parametric_plot3d([cos(u)*(1+v*cos(u/2)), sin(u)*(1+v*cos(u/2)), 0.2*v*sin(u/2)], (u,0, 4*pi+0.5), (v,0, 0.3),plot_points=[200,200])
p.show(viewer='tachyon')
///
}}}

{{{id=130|
# Mbius strip:
u,v = var("u,v")
parametric_plot3d([cos(u)*(1+v*cos(u/2)), sin(u)*(1+v*cos(u/2)), 0.2*v*sin(u/2)], (u,0, 4*pi+0.5), (v,0, 0.3),plot_points=[140,140])
///
}}}

<h2>Finite Field Arithmetic</h2>

{{{id=4|
k.<a> = GF(2^8)
k
///

Finite Field in a of size 2^8
}}}

{{{id=64|
latex(k)
///

\mathbf{F}_{2^{8}}
}}}

{{{id=65|
show(k)
///

<html><div class="math">\mathbf{F}_{2^{8}}</div></html>
}}}

{{{id=62|
P.<x> = GF(3)['x']
while True:
  p = P.random_element(degree=5)
  if p.is_irreducible() and p.degree() == 5:
    break
p
///

2*x^5 + x^4 + 2*x^3 + 2*x^2 + 2*x + 1
}}}

{{{id=66|
p = p/p.leading_coefficient()
p
///

x^5 + 2*x^4 + x^3 + x^2 + x + 2
}}}

{{{id=63|
k.<a> = GF(3^5, modulus=p)
k.modulus()
///

x^5 + 2*x^4 + x^3 + x^2 + x + 2
}}}

<h2>Dense Linear Algebra over the Rationals and Integers</h2>

The NTRUEncrypt Public Key Cryptosystem is based on the hard mathematical problem of finding very short vectors in
lattices of very high dimension.

Generate a ntru-like lattice of dimension ($400 \times 400$), with the
coefficients $h_i$ chosen as random $130$ bits integers and parameter $q=35$:

$$
\left( \begin{array}{cccccccc}
 1 & 0 & \dots & 0 & h_0  &     h_1 & \dots & h_{d-1}\\
 0 & 1 & \dots & 0 & h_1  &     h_2 & \dots & h_0     \\
 \dots & \dots & \dots & \dots & \dots & \dots & \dots & \dots \\
 0 & 0 & \dots & 1 & h_{d-1} & h_0 & \dots & h_{d-1}\\
 0 & 0 & \dots & 0 & q   &      0  & \dots & 0     \\
 0 & 0 & \dots & 0 & 0   &      q  & \dots & 0     \\
 \dots & \dots & \dots & \dots & \dots & \dots & \dots & \dots \\
 0 & 0 & \dots & 0 & 0 &       0  & \dots & q     \\
\end{array} \right)
$$

{{{id=74|
# this is not guaranteed to be LLL reduced (this is a demo so it has to be really quick)
from sage.libs.fplll.fplll import gen_ntrulike
A = gen_ntrulike(400,400,35)
time B = A.LLL(algorithm='fpLLL:fast')
///

Time: CPU 0.51 s, Wall: 0.54 s
}}}

Sage ships NTL and fpLLL for LLL (and BKZ) reduction.

{{{id=117|
A = random_matrix(ZZ, 70, 70, x=-2^16,y=2^16, density=0.05)
time B = A.LLL(algorithm='NTL:LLL',fp='rr')
time C = A.LLL(algorithm='fpLLL:wrapper')
time _ = C.BKZ()
///

Time: CPU 2.86 s, Wall: 2.94 s
Time: CPU 1.49 s, Wall: 1.51 s
Time: CPU 0.04 s, Wall: 0.04 s
}}}

For some matrix shapes over $\mathbb{Q}$ Sage is very fast when computing the row echelon form.

{{{id=15|
n = 100
a = random_matrix(QQ,n, n+1, num_bound=2^64, den_bound=1)
time a.echelonize()
///

Time: CPU 0.15 s, Wall: 0.15 s
}}}

{{{id=26|
%magma
n := 100;
a := RMatrixSpace(RationalField(), n,n+1)![Random(1,2^64): i in [1..n*(n+1)]];
time e := EchelonForm(a);
///



Time: 2.100
}}}

<h2>Dense Linear Algebra over Finite Fields</h2>

{{{id=69|
A = random_matrix(GF(32003),2000,2000)
B = random_matrix(GF(32003),2000,2000)
time C = A._multiply_linbox(B)
///

Time: CPU 2.48 s, Wall: 2.54 s
}}}

{{{id=118|
%magma
n := 2000;
A := RandomMatrix(GF(32003), n,n);
B := RandomMatrix(GF(32003), n,n);
time C := A*B;
///




Time: 2.580
}}}

{{{id=70|
time E = A.echelon_form()
///

CPU time: 1.52 s,  Wall time: 1.56 s
}}}

{{{id=119|
%magma
time E:=EchelonForm(A);
///

Time: 1.720
}}}

{{{id=35|
n = 10000
A = random_matrix(GF(2),n,n)
time E = A.echelon_form()
///

Time: CPU 1.53 s, Wall: 1.56 s
}}}

{{{id=36|
%magma
n := 10000;
A := RandomMatrix(GF(2), n, n);
time E := EchelonForm(A);
///



Time: 2.850
}}}

{{{id=37|
n = 10000
A = random_matrix(GF(2),n,n)
B = random_matrix(GF(2),n,n)
time C = A*B
///

Time: CPU 1.54 s, Wall: 1.55 s
}}}

{{{id=38|
%magma
n := 10000;
A := RandomMatrix(GF(2), n, n);
B := RandomMatrix(GF(2), n, n);
time C := A*B;
///




Time: 2.250
}}}

<h2>Sparse Linear Algebra over Finite Fields</h2>

{{{id=12|
A = random_matrix(GF(127),10000,10000,density=2.0/10000, sparse=True)
time A.rank()
time A.echelonize()
///

Time: CPU 1.06 s, Wall: 1.06 s
Time: CPU 1.74 s, Wall: 1.74 s
}}}

{{{id=91|
A = random_matrix(GF(127),1500,1500,density=10/1500, sparse=True)
b = random_matrix(GF(127),1500,1)
time c = A\b
(A*c) == b
///

Time: CPU 3.84 s, Wall: 3.92 s
True
}}}

{{{id=89|
n = 300
A = random_matrix(GF(127),n,n+100,sparse=True,density=2/n)
A.echelonize()
A.visualize_structure()
///
}}}

{{{id=90|
sr = mq.SR(4,2,2,4,gf2=True, allow_zero_inversions=True)
F,s = sr.polynomial_system() 
A,v = F.coefficient_matrix()
A.visualize_structure(maxsize=1000)
///
}}}

<h2>Factoring</h2>

{{{id=71|
time factor(next_prime(2^40) * next_prime(2^300),verbose=0)
///

1099511627791 * 2037035976334486086268445688409378161051468393665936250636140449354381299763336706183397533
CPU time: 3.75 s,  Wall time: 3.81 s
}}}

{{{id=73|
time ecm.factor(next_prime(2^40) * next_prime(2^300))
///

[1099511627791, 2037035976334486086268445688409378161051468393665936250636140449354381299763336706183397533]
CPU time: 0.16 s,  Wall time: 0.58 s
}}}

{{{id=16|
v,t = qsieve(next_prime(2^90)*next_prime(2^91),time=True)
print v, t[:4]
///

[1237940039285380274899124357, 2475880078570760549798248507] 3.50
}}}

<h2>Elliptic Curves</h2>

{{{id=13|
e = EllipticCurve("37a") # Cremona Label
show(e)
///

<html><div class="math">y^2 + y = x^3 - x </div></html>
}}}

{{{id=111|
e.lift_x(2)
///

(2 : 2 : 1)
}}}

{{{id=75|
show(plot(e))
///
}}}

{{{id=58|
e.a_invariants()
///

[0, 0, 1, -1, 0]
}}}

The Fourier coefficients $a_p$ of the modular form attached to this elliptic curve, for all primes $p \leq n$.

{{{id=67|
print e.aplist(20)
time n = e.aplist(10^6)
///

[-2, -3, -2, -1, -5, -2, 0, 0]
Time: CPU 4.69 s, Wall: 4.78 s
}}}

{{{id=77|
%magma
print GetVersion();
E := EllipticCurve([0,0,1,-1,0]);
print TracesOfFrobenius(E, 20);
time n := TracesOfFrobenius(E,10^6);
///

2 14 14

[ -2, -3, -2, -1, -5, -2, 0, 0 ]
Time: 5.420
}}}

{{{id=120|
sage: E = elliptic_curves.rank(3)[0]
sage: E.integral_points(both_signs=False)
///

[(-3 : 0 : 1), (-2 : 3 : 1), (-1 : 3 : 1), (0 : 2 : 1), (1 : 0 : 1), (2 : 0 : 1), (3 : 3 : 1), (4 : 6 : 1), (8 : 21 : 1), (11 : 35 : 1), (14 : 51 : 1), (21 : 95 : 1), (37 : 224 : 1), (52 : 374 : 1), (93 : 896 : 1), (342 : 6324 : 1), (406 : 8180 : 1), (816 : 23309 : 1)]
}}}

{{{id=79|
@interact
def f(p=primes(2,500)):
    E = EllipticCurve('37a')
    show(E)
    show(plot(E.change_ring(GF(p)),pointsize=30), \
         axes=False, frame=True, gridlines="automatic", aspect_ratio=1, gridlinesstyle={'rgbcolor':(0.7,0.7,0.7)})
///

<html><!--notruncate--><div padding=6 id='div-interact-79'> <table width=800px height=20px bgcolor='#c5c5c5'
                 cellpadding=15><tr><td bgcolor='#f9f9f9' valign=top align=left><table><tr><td align=right><font color="black">p&nbsp;</font></td><td><table><tr><td>
    	<div id='slider-p-79' class='ui-slider-3' style='padding:0px;margin:0px;'><span class='ui-slider-handle'></span></div>
    	</td><td><font color='black' id='slider-p-79-lbl'></font></td></tr></table><script>(function(){ var values = ["2","3","5","7","11","13","17","19","23","29","31","37","41","43","47","53","59","61","67","71","73","79","83","89","97","101","103","107","109","113","127","131","137","139","149","151","157","163","167","173","179","181","191","193","197","199","211","223","227","229","233","239","241","251","257","263","269","271","277","281","283","293","307","311","313","317","331","337","347","349","353","359","367","373","379","383","389","397","401","409","419","421","431","433","439","443","449","457","461","463","467","479","487","491","499"]; setTimeout(function() {
    $('#slider-p-79').slider({
    	stepping: 1, minValue: 0, maxValue: 94, startValue: 0,
    	change: function () { var position = Math.ceil($('#slider-p-79').slider('value')); if(values!=null) $('#slider-p-79-lbl').text(values[position]); interact(79, "sage.server.notebook.interact.update(79, \"p\", 7, sage.server.notebook.interact.standard_b64decode(\""+encode64(position)+"\"), globals())"); },
    	slide: function() { if(values!=null) $('#slider-p-79-lbl').text(values[Math.ceil($('#slider-p-79').slider('value'))]); }
    });
    if(values != null) $('#slider-p-79-lbl').text(values[Math.ceil($('#slider-p-79').slider('value'))]);
    }, 1); })();</script></td></tr>
</table><div id='cell-interact-79'><?__SAGE__START>
        <table border=0 bgcolor='#white' width=100% height=100%>
        <tr><td bgcolor=white align=left valign=top><pre><?__SAGE__TEXT></pre></td></tr>
        <tr><td  align=left valign=top><?__SAGE__HTML></td></tr>
        </table><?__SAGE__END></div></td>
                 </tr></table></div>
                 </html>
}}}

{{{id=78|
k = GF(next_prime(10^7))
E = EllipticCurve(k, [k.random_element(),k.random_element()])
E
///

Elliptic Curve defined by y^2  = x^3 + 3248759*x + 6256184 over Finite Field of size 10000019
}}}

{{{id=82|
P = E.random_element()
P.order()
///

666730
}}}

{{{id=81|
E.cardinality()
///

10000950
}}}

{{{id=86|
2*P + P
///

(2858307 : 6660064 : 1)
}}}

<h2>Number Fields</h2>

{{{id=121|
x = var('x')
K.<a> = NumberField(x^3 - 2)
L.<b> = K.galois_closure()
L
///

Number Field in b with defining polynomial x^6 + 40*x^3 + 1372
}}}

{{{id=41|
K.complex_embeddings()
///

[
Ring morphism:
  From: Number Field in a with defining polynomial x^3 - 2
  To:   Complex Double Field
  Defn: a |--> -0.629960524947 - 1.09112363597*I,
Ring morphism:
  From: Number Field in a with defining polynomial x^3 - 2
  To:   Complex Double Field
  Defn: a |--> -0.629960524947 + 1.09112363597*I,
Ring morphism:
  From: Number Field in a with defining polynomial x^3 - 2
  To:   Complex Double Field
  Defn: a |--> 1.25992104989
]
}}}

<h2>p-Adic Numbers</h2>

{{{id=102|
R = Zp(5)
e = R(3125346)
f = R(5*34234234)
t = cputime()
for i in xrange(10^6):
  z = e*f
cputime(t)
///

0.42393599999999765
}}}

{{{id=101|
%magma
R := pAdicRing(5);
e := R!3125346;
f := R!5*34234234;
time for i in [1..10^6] do
  z := e*f;
end for
///






Time: 0.670
}}}

{{{id=100|
gp.eval("e = %s"%(e._gp_().name()))
gp.eval("f = %s"%(f._gp_().name()))
///

'4*5 + 5^2 + 4*5^3 + 3*5^4 + 4*5^5 + 4*5^6 + 3*5^8 + 2*5^9 + 2*5^10 + 3*5^11 + O(5^21)'
}}}

{{{id=103|
%gp
gettime;
for(i=1,10^6,z=e*f);
gettime/1000.0
///



0.69800000000000000000000000000000000000
}}}

<h2>Graph Theory</h2>

{{{id=17|
D = graphs.DodecahedralGraph()
D.show()
///
}}}

{{{id=18|
D.show3d(viewer='tachyon')
///
}}}

{{{id=122|
D.show3d()
///
}}}

{{{id=19|
gamma = SymmetricGroup(20).random_element()
E = D.copy()
E.relabel(gamma)
D.is_isomorphic(E)
///

True
}}}

{{{id=20|
D.radius()
///

5
}}}

<h2>Group Theory</h2>

{{{id=132|
G = PermutationGroup([[(1,2,3),(4,5)], (3,4)]);
G
///

Permutation Group with generators [(1,2,3)(4,5), (3,4)]
}}}

{{{id=46|
G.order()
///

120
}}}

{{{id=133|
G.is_abelian()
///

False
}}}

{{{id=134|
G.derived_series()
///

[Permutation Group with generators [(1,2,3)(4,5), (3,4)], Permutation Group with generators [(1,5)(3,4), (1,5)(2,3), (1,5,4)]]
}}}

{{{id=135|
G.random_element()
///

(1,5)(2,4)
}}}

{{{id=136|
G.center()
///

Permutation Group with generators [()]
}}}

{{{id=138|
SL4 = SL(4,GF(127)); SL4
///

Special Linear Group of degree 4 over Finite Field of size 127
}}}

{{{id=137|
SL4.order()
///

36060245035822158462416588636160
}}}

{{{id=139|
M = SL4.as_matrix_group(); M
///

Matrix group over Finite Field of size 127 with 2 generators: 
 [[[3, 0, 0, 0], [0, 85, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]], [[126, 0, 0, 1], [126, 0, 0, 0], [0, 126, 0, 0], [0, 0, 126, 0]]]
}}}

{{{id=47|
M.is_finite()
///

True
}}}

<h2>Univariate Polynomials over $\mathbf{Z}$</h2>

{{{id=23|
P.<x> = ZZ[]
deg = 32; coeff=64
f = P.random_element(degree=deg,x=0,y=2^coeff)
g = P.random_element(degree=deg,x=0,y=2^coeff)
///
}}}

{{{id=107|
type(f)
///

<type 'sage.rings.polynomial.polynomial_integer_dense_flint.Polynomial_integer_dense_flint'>
}}}

{{{id=24|
%time
for _ in xrange(10^4):
   w = f*g
///

CPU time: 0.14 s,  Wall time: 0.14 s
}}}

{{{id=25|
gp.eval('f = Pol(%s)'%f.list())
_ = gp.eval('g = Pol(%s)'%g.list())
///
}}}

{{{id=27|
%gp
gettime; for(i=1,10^4,w=f*g); gettime/1000.0
///

0.90100000000000000000000000000000000000
}}}

{{{id=28|
%magma
R<x> := PolynomialRing(IntegerRing());
///
}}}

{{{id=29|
magma.eval('f := R!%s'%f.list())
_ = magma.eval('g := R!%s'%g.list())
///
}}}

{{{id=30|
%magma
time for i in [1..10^4] do w := f*g; end for;
///

Time: 1.430
}}}

{{{id=31|
# NTL
ff = ntl.ZZX(f.list())
gg = ntl.ZZX(g.list())
///
}}}

{{{id=39|
time for i in xrange(10^4): w = ff*gg
///

CPU time: 0.78 s,  Wall time: 0.78 s
}}}

<h2>Multivariate Polynomial Rings over Finite Fields</h2>

{{{id=92|
#In SAGE
P.<x,y,z> = PolynomialRing(GF(32003),3)
p = (x + y + z + 1)^20 # the Fateman fastmult benchmark
q = p + 1
time r = p*q
///

Time: CPU 0.11 s, Wall: 0.11 s
}}}

{{{id=32|
%magma
P<x,y,z> := PolynomialRing(GF(32003),3);
p:= (x + y + z + 1)^20;
q:= p + 1;
time r:= p*q;
///




Time: 0.270
}}}

{{{id=33|
#In SAGE
P.<x,y,z> = PolynomialRing(QQ,3)
p = (x + y + z + 1)^20 # the Fateman fastmult benchmark
q = p + 1
time r = p*q
///

Time: CPU 1.03 s, Wall: 1.05 s
}}}

{{{id=34|
%magma
P<x,y,z> := PolynomialRing(RationalField(),3);
p := (x + y + z + 1)^20;
q := p + 1;
time r := p*q;
///




Time: 0.430
}}}

{{{id=123|
P = PolynomialRing(GF(32003),7,'x')
I = sage.rings.ideal.Cyclic(P,7)
t = cputime()
gb = I.groebner_basis('libsingular:std')
print 'Sage/Singular', cputime(t)

I = sage.rings.ideal.Cyclic(P,7)
t = magma.cputime()
gb = I.groebner_basis('magma:GroebnerBasis')
print 'MAGMA', magma.cputime(t)
///

Sage/Singular 2.188667
MAGMA 0.39
}}}

{{{id=124|
P.<x, y, z> = PolynomialRing(ZZ, 3)
I = ideal( x^2 - 3*y, y^3 - x*y, z^3 - x, x^4 - y*z + 1 )
R = P.change_ring( QQ )
I.change_ring( R ).groebner_basis()
///

[1]
}}}

{{{id=61|
@interact
def _(p=primes(1000)):
  gb0 = sorted(I.groebner_basis(),reverse=True)
  show(gb0)
  n = ZZ(gb0[-1])
  html("<div align='center'>$%s = %s</div>"%(latex(n),latex(factor(n))))
  J = I.change_ring(I.ring().change_ring(GF(p)))
  for f in J.groebner_basis():
    show(f)
///

<html><!--notruncate--><div padding=6 id='div-interact-61'> <table width=800px height=20px bgcolor='#c5c5c5'
                 cellpadding=15><tr><td bgcolor='#f9f9f9' valign=top align=left><table><tr><td align=right><font color="black">p&nbsp;</font></td><td><table><tr><td>
    	<div id='slider-p-61' class='ui-slider-3' style='padding:0px;margin:0px;'><span class='ui-slider-handle'></span></div>
    	</td><td><font color='black' id='slider-p-61-lbl'></font></td></tr></table><script>(function(){ var values = ["2","3","5","7","11","13","17","19","23","29","31","37","41","43","47","53","59","61","67","71","73","79","83","89","97","101","103","107","109","113","127","131","137","139","149","151","157","163","167","173","179","181","191","193","197","199","211","223","227","229","233","239","241","251","257","263","269","271","277","281","283","293","307","311","313","317","331","337","347","349","353","359","367","373","379","383","389","397","401","409","419","421","431","433","439","443","449","457","461","463","467","479","487","491","499","503","509","521","523","541","547","557","563","569","571","577","587","593","599","601","607","613","617","619","631","641","643","647","653","659","661","673","677","683","691","701","709","719","727","733","739","743","751","757","761","769","773","787","797","809","811","821","823","827","829","839","853","857","859","863","877","881","883","887","907","911","919","929","937","941","947","953","967","971","977","983","991","997"]; setTimeout(function() {
    $('#slider-p-61').slider({
    	stepping: 1, minValue: 0, maxValue: 167, startValue: 0,
    	change: function () { var position = Math.ceil($('#slider-p-61').slider('value')); if(values!=null) $('#slider-p-61-lbl').text(values[position]); interact(61, "sage.server.notebook.interact.update(61, \"p\", 8, sage.server.notebook.interact.standard_b64decode(\""+encode64(position)+"\"), globals())"); },
    	slide: function() { if(values!=null) $('#slider-p-61-lbl').text(values[Math.ceil($('#slider-p-61').slider('value'))]); }
    });
    if(values != null) $('#slider-p-61-lbl').text(values[Math.ceil($('#slider-p-61').slider('value'))]);
    }, 1); })();</script></td></tr>
</table><div id='cell-interact-61'><?__SAGE__START>
        <table border=0 bgcolor='#white' width=100% height=100%>
        <tr><td bgcolor=white align=left valign=top><pre><?__SAGE__TEXT></pre></td></tr>
        <tr><td  align=left valign=top><?__SAGE__HTML></td></tr>
        </table><?__SAGE__END></div></td>
                 </tr></table></div>
                 </html>
}}}

<h2>Algebraic Cryptanalysis</h2>

{{{id=93|
sr = mq.SR(2,1,1,4,gf2=True)
sr
///

SR(2,1,1,4)
}}}

{{{id=95|
F,s = sr.polynomial_system()
F
///

Polynomial System with 104 Polynomials in 36 Variables
}}}

{{{id=94|
gb = F.groebner_basis()
Ideal(gb).variety()
///

[{s001: 1, s103: 1, s101: 0, x103: 0, s000: 1, x101: 0, k003: 0, k100: 1, k001: 0, k200: 0, x200: 1, k202: 1, x202: 1, w102: 0, w100: 1, w201: 0, s002: 0, w203: 1, k101: 1, s102: 1, s100: 0, x102: 1, x100: 0, k002: 1, k000: 1, x201: 1, k201: 0, x203: 0, k203: 0, k103: 0, w103: 1, k102: 1, w101: 0, w200: 0, s003: 0, w202: 1}]
}}}

<h2>Numerical Optimisation</h2>
For a simple quadratic programming example, if we want to minimize
$$        2x_1^2 + x_2^2 + x_1x_2 + x_1 + x_2$$
subject to
$$        x_1 \geq 0$$
$$        x_2 \geq 0$$	
$$        x_1 + x_2 = 1$$

{{{id=48|
from cvxopt.base import matrix as m
from cvxopt import solvers

Q = 2r*m([ [2r, .5r], [.5r, 1r] ])
p = m([1.0r, 1.0r])
G = m([[-1.0r,0.0r],[0.0r,-1.0r]])
h = m([0.0r,0.0r])
A = m([1.0r, 1.0r], (1r,2r))
b = m(1.0r)
sol=solvers.qp(Q, p, G, h, A, b)
print sol['x']
///

     pcost       dcost       gap    pres   dres
 0:  0.0000e+00  0.0000e+00  3e+00  1e+00  0e+00
 1:  1.0776e+00  1.3668e+00  6e-01  4e-01  2e-16
 2:  1.8460e+00  1.8291e+00  6e-02  2e-02  4e-16
 3:  1.8741e+00  1.8681e+00  8e-03  1e-03  3e-16
 4:  1.8750e+00  1.8748e+00  2e-04  3e-05  5e-16
 5:  1.8750e+00  1.8750e+00  3e-06  2e-07  1e-16
 6:  1.8750e+00  1.8750e+00  3e-08  1e-09  6e-16
   2.5000e-01
   7.5000e-01
}}}

<h2>Statistics</h2>

{{{id=140|
S = AlphabeticStrings()
k = Permutations(range(26)).random_element()
K = S(k)
E = SubstitutionCryptosystem(S)
e = E(K)
///
}}}

{{{id=146|
m = "Sage can be used to study general and advanced, pure and applied mathematics. This includes a huge range of mathematics, including algebra, calculus, elementary to very advanced number theory, cryptography, numerical computation, commutative algebra, group theory, combinatorics, graph theory, exact linear algebra and much more. It combines various software packages and seamlessly integrates their functionality into a common experience. It is well suited  for education, studying and research. The interface is a notebook in a web-browser or the command-line. Using the notebook, Sage connects either locally to your own Sage installation or to a Sage server on the network. Inside the Sage notebook you can create embedded graphics, beautifully typeset mathematical expressions, add and delete input, and share your work across the network. The following showcase presents some of Sage's capabilities, screenshots and gives you an overall impression of what Sage is. The examples show the lines of code in Sage on the left side, accompanied by an explanation on the right. They only show the very basic concepts of how Sage works. Please refer to the documentation material for more detailed explanations or visit the library to see Sage in action."
m = S("".join([c.upper() for c in m if c.upper() in "ABCDEFGHIJKLMNOPQRSTUVWXYZ"]))
m
///

SAGECANBEUSEDTOSTUDYGENERALANDADVANCEDPUREANDAPPLIEDMATHEMATICSTHISINCLUDESAHUGERANGEOFMATHEMATICSINCLUDINGALGEBRACALCULUSELEMENTARYTOVERYADVANCEDNUMBERTHEORYCRYPTOGRAPHYNUMERICALCOMPUTATIONCOMMUTATIVEALGEBRAGROUPTHEORYCOMBINATORICSGRAPHTHEORYEXACTLINEARALGEBRAANDMUCHMOREITCOMBINESVARIOUSSOFTWAREPACKAGESANDSEAMLESSLYINTEGRATESTHEIRFUNCTIONALITYINTOACOMMONEXPERIENCEITISWELLSUITEDFOREDUCATIONSTUDYINGANDRESEARCHTHEINTERFACEISANOTEBOOKINAWEBBROWSERORTHECOMMANDLINEUSINGTHENOTEBOOKSAGECONNECTSEITHERLOCALLYTOYOUROWNSAGEINSTALLATIONORTOASAGESERVERONTHENETWORKINSIDETHESAGENOTEBOOKYOUCANCREATEEMBEDDEDGRAPHICSBEAUTIFULLYTYPESETMATHEMATICALEXPRESSIONSADDANDDELETEINPUTANDSHAREYOURWORKACROSSTHENETWORKTHEFOLLOWINGSHOWCASEPRESENTSSOMEOFSAGESCAPABILITIESSCREENSHOTSANDGIVESYOUANOVERALLIMPRESSIONOFWHATSAGEISTHEEXAMPLESSHOWTHELINESOFCODEINSAGEONTHELEFTSIDEACCOMPANIEDBYANEXPLANATIONONTHERIGHTTHEYONLYSHOWTHEVERYBASICCONCEPTSOFHOWSAGEWORKSPLEASEREFERTOTHEDOCUMENTATIONMATERIALFORMOREDETAILEDEXPLANATIONSORVISITTHELIBRARYTOSEESAGEINACTION
}}}

{{{id=145|
c = e(m)
c
///

KCNUVCXRUIKUWOAKOIWGNUXUQCPCXWCWSCXVUWFIQUCXWCFFPMUWDCOHUDCOMVKOHMKMXVPIWUKCHINUQCXNUALDCOHUDCOMVKMXVPIWMXNCPNURQCVCPVIPIKUPUDUXOCQGOASUQGCWSCXVUWXIDRUQOHUAQGVQGFOANQCFHGXIDUQMVCPVADFIOCOMAXVADDIOCOMSUCPNURQCNQAIFOHUAQGVADRMXCOAQMVKNQCFHOHUAQGUBCVOPMXUCQCPNURQCCXWDIVHDAQUMOVADRMXUKSCQMAIKKALOJCQUFCVECNUKCXWKUCDPUKKPGMXOUNQCOUKOHUMQLIXVOMAXCPMOGMXOACVADDAXUBFUQMUXVUMOMKJUPPKIMOUWLAQUWIVCOMAXKOIWGMXNCXWQUKUCQVHOHUMXOUQLCVUMKCXAOURAAEMXCJURRQAJKUQAQOHUVADDCXWPMXUIKMXNOHUXAOURAAEKCNUVAXXUVOKUMOHUQPAVCPPGOAGAIQAJXKCNUMXKOCPPCOMAXAQOACKCNUKUQSUQAXOHUXUOJAQEMXKMWUOHUKCNUXAOURAAEGAIVCXVQUCOUUDRUWWUWNQCFHMVKRUCIOMLIPPGOGFUKUODCOHUDCOMVCPUBFQUKKMAXKCWWCXWWUPUOUMXFIOCXWKHCQUGAIQJAQECVQAKKOHUXUOJAQEOHULAPPAJMXNKHAJVCKUFQUKUXOKKADUALKCNUKVCFCRMPMOMUKKVQUUXKHAOKCXWNMSUKGAICXASUQCPPMDFQUKKMAXALJHCOKCNUMKOHUUBCDFPUKKHAJOHUPMXUKALVAWUMXKCNUAXOHUPULOKMWUCVVADFCXMUWRGCXUBFPCXCOMAXAXOHUQMNHOOHUGAXPGKHAJOHUSUQGRCKMVVAXVUFOKALHAJKCNUJAQEKFPUCKUQULUQOAOHUWAVIDUXOCOMAXDCOUQMCPLAQDAQUWUOCMPUWUBFPCXCOMAXKAQSMKMOOHUPMRQCQGOAKUUKCNUMXCVOMAX
}}}

{{{id=149|
c = e(m)
c = map(ord,str(c))
c[:10]
///

[75, 67, 78, 85, 86, 67, 88, 82, 85, 73]
}}}

{{{id=148|
from rpy import r
r.png('histogram.png',width=900,height=480)
r.hist(c,r.seq(min(c),max(c),1),main="Histogram",col="lightblue", prob=True, xlab="ord(c)")
r.dev_off()
///

{'null device': 1}
}}}

{{{id=147|
m[c.index(85)]
///

E
}}}

<h2>Combinatorics</h2>

{{{id=53|
C = Combinations(range(5)); C
///

Combinations of [0, 1, 2, 3, 4]
}}}

{{{id=106|
C.list()
///

[[], [0], [1], [2], [3], [4], [0, 1], [0, 2], [0, 3], [0, 4], [1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4], [0, 1, 2], [0, 1, 3], [0, 1, 4], [0, 2, 3], [0, 2, 4], [0, 3, 4], [1, 2, 3], [1, 2, 4], [1, 3, 4], [2, 3, 4], [0, 1, 2, 3], [0, 1, 2, 4], [0, 1, 3, 4], [0, 2, 3, 4], [1, 2, 3, 4], [0, 1, 2, 3, 4]]
}}}

{{{id=54|
C.unrank(10)
///

[1, 2]
}}}

<h2>Interfaces</h2>

{{{id=112|
%gap
a := 1;
for i in [1..100] do if IsPrime(i) then a:=a+1; else a:=a+2; fi;  od; a;
///

1
176
}}}

{{{id=113|
%singular
int a = 1; int i = 1;
for(i=1; i<=100; i=i+1) { if(prime(i) == i){  a=a+1; } else {a=a+2;} };
a;
///



176
}}}

{{{id=114|
%gp
a=1; for(X=1,100,if(isprime(X),a+=1,a+=2)); a
///

176
}}}

{{{id=115|
a= gap(1) # or gp(1), magma(1), singular(1)
for i in range(100):
    if gap(i+1).IsPrime():
        a+=1
    else:
        a+=2
a
///

176
}}}

{{{id=56|
pari(a).factor()
///

[2, 4; 11, 1]
}}}

<h2>Sequences of Integers</h2>

{{{id=126|
for sq in sloane_find([2,3,5,7], 2):
  print sq[0], sq[1]
///

Searching Sloane's online database...
40 The prime numbers.
41 a(n) = number of partitions of n (the partition numbers).
}}}

{{{id=131|

///
}}}

{{{id=142|

///
}}}

{{{id=143|

///
}}}