Code takes time to execute, points error but then displays the result

Asked

Viewed 87 times

-1

Code on net Beans runs, but it takes time to show the result. Error appears in the netbeans console, but if I leave the program running after a while it shows the result:

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

int main( int argc, char** argv )
{
    int res = 0, contador = 0;

    for (int num = 20; ; num++) {
        for (int i = 1; i <= 20; i++) {
            if (num % i == 0) {
                contador++;
            }
        }
        if (contador == 20) {
           res = num;
           break;
        }
        contador = 0;
    }

    printf("%d\n", res);

    return (EXIT_SUCCESS );
}

When running the program this appears (netbeans console error): imagem But if I leave the program running for some time (+- 40, 50 seconds) it shows the result even if it gives error: ![funcionando What should I do to optimize / solve this problem? PS: The result is right, was checked in the project’s responses!!!

  • Note that you do the if test (counter == 20) { after a loop that can increment the counter variable. It may be that within the loop the increment of the counter variable may exceed 20. I believe that the if test (counter >= 20) { is safer.

1 answer

1


This algorithm finds the lowest common multiple of the first n natural numbers.

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

int main( int argc, char** argv )
{
    int n = 20;
    int res = 1;
    int prev;

    for (int i = 1; i <= n; i++) {
        prev = res;
        while (res % i > 0) {
            res += prev;
        }
    }

    printf("%d\n", res);

    return (EXIT_SUCCESS );
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.