Implementing a function in PARI/GP

2k Views Asked by At

I want to define a function:

$$g(n)= \begin{cases} +1 & \text{if $n=1$},\\ +1 & \text{if $n$ is an odd indexed prime}, \\ -1 & \text{if $n$ is an even indexed prime},\\ (-1)^r & \text{if $n$ is composite and contains $r$ even indexed prime factors},\\ \end{cases}$$

in PARI/GP. By odd indexed primes I mean $p_{2k-1}$, i.e. 2, 5, 11, 17, 23... corresponding to $p_1, p_3, p_5, p_7, p_9 \ldots $, where $p_n$ is the $n$th prime number. Similarly even indexed primes are $p_{2k}$ i.e. 3, 7, 13, 19, 29... corresponding to $p_2, p_4, p_6, p_8, p_{10} \ldots $.

First few values of $g(n)$ corresponding to $n=1, 2, 3, 4 \ldots $ are $1, 1,-1, 1, 1,-1,-1, 1, 1, 1, 1,-1,-1,-1,-1, 1, 1, 1, -1, 1, 1, 1, 1,-1, 1,-1,-1,-1,-1,-1, 1, 1 \ldots$

Can anybody tell me a simple program to implement this in PARI GP :-D

1

There are 1 best solutions below

4
On BEST ANSWER

Instead of trying to decompose $n$ into its prime divisors, I would iterate through the prime numbers to see which one divides $n$. Code-wise, this is probably more efficient as the first method probably requires a more complex mechanism to determine the index of the prime divisors.

Code:

compute(n) =
{
    g = 1;
    index = 0;
    p = 0;
    while(p < n, 
        p = nextprime(p + 1); 
        index += 1;
        while(n % p == 0, n = n / p; if (index % 2 == 0, g *= -1));
    );
    printf("%d\n", g);
}

for(i = 1, 200, compute(i));

Output for the first 200 values of $n$:

1, 1, -1, 1, 1, -1, -1, 1, 1, 1, 1, -1, -1, -1, -1, 1, 1, 1, -1, 1, 1, 1, 1, -1,
1, -1, -1, -1, -1, -1, 1, 1, -1, 1, -1, 1, -1, -1, 1, 1, 1, 1, -1, 1, 1, 1, 1,
-1, 1, 1, -1, -1, -1, -1, 1, -1, 1, -1, 1, -1, -1, 1, -1, 1, -1, -1, 1, 1, -1, 
-1, -1, 1, 1, -1, -1, -1, -1, 1, -1, 1, 1, 1, 1, 1, 1, -1, 1, 1, -1, 1, 1, 1, -1,
1, -1, -1, 1, 1, 1, 1, -1, -1, 1, -1, 1, -1, -1, -1, 1, 1, 1, -1, -1, 1, 1, -1,
-1, 1, -1, -1, 1, -1, -1, 1, 1, -1, 1, 1, 1, -1, -1, -1, 1, 1, -1, 1, 1, -1, -1,
-1, -1, -1, -1, 1, -1, 1, -1, -1, 1, -1, -1, -1, 1, -1, 1, 1, 1, -1, 1, 1, -1,
1, -1, 1, -1, 1, 1, 1, 1, 1, -1, -1, -1, 1, -1, 1, -1, -1, 1, 1, -1, 1, 1, 1, 
-1, -1, 1, 1, 1, -1, 1, -1, -1, 1, 1, 1, 1, 1, -1, 1