The Jacobi symbol is a multiplicative function that generalizes the Legendre symbol. Specifically, the Jacobi symbol (a | n) equals the product of the Legendre symbols (a | p_i)^(k_i), where n = p_1^(k_1)*p_2^(k_2)*...*p_i^(k_i) and the Legendre symbol (a | p) denotes the value of a ^ ((p-1)/2) (mod p)

 (a | p) ≡   1     if a is a square (mod p)
 (a | p) ≡ -1     if a is not a square (mod p)
 (a | p) ≡   0     if a ≡ 0 
If n is prime, then the Jacobi symbol (a | n) equals the Legendre symbol (a | n).

Task

Calculate the Jacobi symbol (a | n).

Reference

 Wikipedia article on Jacobi symbol.
function gcdp( a as uinteger, b as uinteger ) as uinteger
    if b = 0 then return a
    return gcdp( b, a mod b )
end function
 
function gcd(a as integer, b as integer) as uinteger
    return gcdp( abs(a), abs(b) )
end function
 
function jacobi( a as uinteger, n as uinteger ) as integer
    if gcd(a, n)<>1 then return 0
    if a = 1 then return 1
    if a>n then return jacobi( a mod n, n )
    if a mod 2 = 0 then
        if n mod 8 = 1 or n mod 8 = 7 then
            return jacobi(a/2, n)
        else
            return -jacobi(a/2, n)
        end if
    end if
    dim as integer q = (-1)^((a-1)/2 * (n-1)/2)
    return q/jacobi(n, a)
end function
 
'print a table
 
function padto( i as ubyte, j as integer ) as string
    return wspace(i-len(str(j)))+str(j)
end function
 
dim as uinteger pn, k, prime(0 to 16) = {3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61}
dim as string outstr = "  k       "
 
for k = 1 to 36
    outstr = outstr + padto(2, k)+"  "
next k
print outstr
print " n"
for pn=0 to 16
    outstr= " "+padto( 2, prime(pn) )+"       "
    for k = 1 to 36
        outstr = outstr + padto(2, jacobi(k, prime(pn))) + "  "
    next k
    print outstr
next pn