我在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;
}
}
}
答案 0 :(得分:0)
以下是两个最常见的循环结构的C
和Assembly
中的一些伪代码。
While
中C
循环的伪代码:
while ([condition]) {
[body]
}
While
中Assembly
循环的伪代码:
begin_loop:
[condition]
test or cmp instruction
jcc end_loop (conditional jmp according to the condition)
[body]
jmp begin_loop
end_loop:
For
中C
循环的伪代码:
for ([initialization]; [condition]; [increment]) {
[body]
}
For
中Assembly
循环的伪代码:
[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
。)