在AT& T装配中筛选Eratosthenes

时间:2014-09-17 13:11:10

标签: c assembly sieve-of-eratosthenes att sieve

我在C中编写了一个简单的程序,使用Sieve of Eratosthenes查找给定范围内的所有素数。在学校,我们目前正在课堂上学习集会,但我无法弄清楚如何编写三个循环。我已经在NASM中找到了它,我之前已经摆弄过,但我们必须使用AT& T.有什么建议我可以用" void sieve()" 做什么?

#include <stdio.h>
#include <stdlib.h>

void sieve(int *, int);

int main()
{
    int *a, n, i;
    n = 46000;
    printf("Enter the range : ");
    scanf("%d", &n);
    a = malloc(sizeof(int)*n);
    sieve(a,n);

    printf("\nThe primes numbers from 1 to %d are: ", n);
    for(i=2; i<=n; i++)
    {
        if(a[i] == 1)
        printf("%d, ", i);
    }
    printf(".\n\n");

    return 0;
}

void sieve(int *a, int n)
{
    int i, j;
    for(i=2; i<=n; i++)
    a[i] = 1;
    for(i=2; i<=n; i++)
    {
        if(a[i] == 1)
        {
            for(j=i; (i*j)<=n; j++)
            a[(i*j)] = 0;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

以下是两个最常见的循环结构的CAssembly中的一些伪代码。

WhileC循环的伪代码:

while ([condition]) {
    [body]
}

WhileAssembly循环的伪代码:

begin_loop:
    [condition]
    test or cmp instruction
    jcc end_loop (conditional jmp according to the condition)
    [body]
    jmp begin_loop
end_loop:

ForC循环的伪代码:

for ([initialization]; [condition]; [increment]) {
    [body]
}

ForAssembly循环的伪代码:

    [initialization]
begin_loop:
    [condition]
    test or cmp instruction
    jcc end_loop (conditional jmp according to the condition)
    [body]
    [increment]
    jmp begin_loop
end_loop:

转换外部循环的一些代码:

for(i=2; i<=n; i++)
{
    if(a[i] == 1)
    {
        for(j=i; (i*j)<=n; j++)
        a[(i*j)] = 0;
    }
}

Assembly

    mov ecx, 2
    mov eax, N (variable n)

begin_loop:
    cmp ecx, eax
    jg end_loop
    lea ebx, A (array)
    test [ebx + i*4], 1 (4 is assuming size of element of A is 4 bytes)
    jnz continue

    # the other loop

continue:
    inc ecx
    jmp begin_loop

end_loop:

注意使用寄存器,如果你需要在循环中间使用寄存器进行其他操作,保存它们的当前值(例如:到push reg的堆栈),并在需要时使用旧值再次恢复(例如:如果它在堆栈中,则为pop reg。)