Introduction

Programming in Ax is introduced here by way of small examples.

Euclidean Algorithm

Given two integers a and b, the Euclidean algorithm computes their greatest common divisor or gcd.

function euclid(a,b)
{
	var r;
	while (b != 0) {
		r = a % b;
		a = b;
		b = r;
	}
	return a;
}

euclid(24,18);
	6
euclid(48,36);
	12

Collatz Numbers

Given a positive integer n, let the next number in the sequence be 3*n+1 if n is odd, or n/2 if n is even. The Collatz conjecture is that this sequence always reaches the number one, at which point it cycles: 4, 2, 1. The program below counts the number of steps until one is reached.

function collatz(n)
{
	if (n < 2) return 0;
	if (n % 2) return collatz(3*n+1) + 1;
	return collatz(n/2) + 1;
}

collatz(1);
	0
collatz(2);
	1
collatz(3);  # 10, 5, 16, 8, 4, 2, 1
	7
A = vector(10);
for (i=0; i < 10; i+=1) A[i] = collatz(i);
A;
	[0, 0, 1, 7, 2, 5, 8, 16, 3, 19]

Matrix Sum of Elements

Given an m x n matrix, we compute the sum of its elements in the function below.

function matrixsum(A)
{
	var i, j, m, n, s;
	if (!type(A,matrix)) return null;
	m = rows(A); n = columns(A); s = 0;
	for (i=0; i < m; i+=1) {
		for (j=0; j < n; j+=1) {
			s += A[i][j];
		}
	}
	return s;
}

A = [[1,2,3],[4,5,6]];
matrixsum(A);
	21