0

这项任务的目标是在 C 中创建一个汇编程序,该程序将找到 2 到 100 之间的素数之间的最大间隙。我的输出是“最大距离是 2 到 3 之间的 1”。我不知道如何解决它,所以我将不胜感激任何帮助。这是我的代码:

#include <stdio.h>
void main() {
int number;
int distance; //Distance between current primes
int max; //Maximum distance between primes
int divisor; //What the current number is being divided by
int firstPrime;
int secondPrime;
int latestPrime; //Most recent prime
int limit; //Upper limit for our program to go to
__asm {
                mov     limit, 100 //Sets loop counter to 100
                mov     max,0 //Sets max distance to 0
                mov     latestPrime, 2 //Sets 2 as the latest prime, since it is the first prime 
                mov     number, 2 //Sets number to 2
                mov     divisor, 2
    top:        mov     ecx, limit //Moves the limit to ecx so it can be compared
                cmp     ecx, number //Checks to see if we have reached the end of the outermost loop
                je      xOut //Exits outermost loop
                mov     ebx, divisor  // need ebx to compare to number, can't use cmp divisor, number
                cmp     ebx, number
                je      prime     // if divisor == number than we did not find a divisor so number is prime
                mov     eax, number  // prepare to do number % divisor
                mov     edx, 0
                div     divisor
                cmp     edx, 0   // if there was no remainder then number is not prime
                je      notprime
                inc     divisor
                jmp     top
    prime:      mov     eax, latestPrime //Temporarily puts latestPrime in eax
                mov     edx, firstPrime //If the distance is not the new max, we want to save the primes with the max distance.
                mov     firstPrime, eax //Moves latestPrime to firstPrime
                mov     eax, number //Temporarily moves number to eax
                mov     ecx, secondPrime //Preserves second prime
                mov     secondPrime, eax //Moves number to secondPrime
                mov     latestPrime, eax //Updates latestPrime
                sub     eax, firstPrime //Gets the distance between the primes
                inc     number //Explain later
                cmp     eax, max //Compares distance to max
                jg      updateMax //If greater than max, go to updateMax
                mov     firstPrime, edx //Else, keep track of the first and second primes
                mov     secondPrime, ecx
                jmp     top //Go back to outside loop
    notPrime:   inc     number //Explain later
                jmp     top //Go back to top of loop
    updateMax:  mov     max, eax //Puts distance in max
                jmp     top //Moves us back to the outer loop
    xOut:       nop
}
printf("Biggest distance is %d between %d and %d", max, firstPrime, secondPrime);
}
4

0 回答 0