Prime number generator in C Announcing the arrival of Valued Associate #679: Cesar Manara ...

Autumning in love

Is there a documented rationale why the House Ways and Means chairman can demand tax info?

Single author papers against my advisor's will?

What computer would be fastest for Mathematica Home Edition?

How to say that you spent the night with someone, you were only sleeping and nothing else?

Interesting examples of non-locally compact topological groups

How should I respond to a player wanting to catch a sword between their hands?

Is it possible to ask for a hotel room without minibar/extra services?

How to colour the US map with Yellow, Green, Red and Blue to minimize the number of states with the colour of Green

How did passengers keep warm on sail ships?

Can't figure this one out.. What is the missing box?

What's the point in a preamp?

New Order #5: where Fibonacci and Beatty meet at Wythoff

How to rotate it perfectly?

Estimated State payment too big --> money back; + 2018 Tax Reform

When is phishing education going too far?

When communicating altitude with a '9' in it, should it be pronounced "nine hundred" or "niner hundred"?

What items from the Roman-age tech-level could be used to deter all creatures from entering a small area?

3 doors, three guards, one stone

What would be Julian Assange's expected punishment, on the current English criminal law?

Why use gamma over alpha radiation?

I'm thinking of a number

Two different pronunciation of "понял"

Can I throw a sword that doesn't have the Thrown property at someone?



Prime number generator in C



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)Codechef: Prime Number GeneratorPython prime number generatorYet another prime number generatorPrime Number Generator algorithm optimizationPrime number generator exercisePrime number generatorPrime Number Sequence generatorLazy prime number generatorPrime Number GeneratorNon-Sieve Prime Number generatorCodechef: Prime Number Generator





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ margin-bottom:0;
}







3












$begingroup$


I have to print numbers between two limits n and m, t times.



I created t variable that stores a number of test cases.



Outer for loop iterates for every test cases.



Inner for loop prints primes from m to n.



Code



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

int is_prime(int);

int main(void) {
int t, m, n;
scanf("%d", &t);
for (int i = 0; i < t; i++) {
scanf("%d %d", &m, &n);
for (int j = m; j <= n; j++) {
if (is_prime(j)) {
printf("%dn", j);
}
}
if (i < t - 1) printf("n");
}

return 0;
}

int is_prime(int num) {
if (num <= 1) return 0;
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) {
return 0;
}
}
return 1;
}


Problem: http://www.spoj.com/problems/PRIME1/



Can I have review?










share|improve this question









$endgroup$












  • $begingroup$
    You might be interested in a similar review I did a while back; a lot of the algorithmic notes there also apply here: codereview.stackexchange.com/questions/165576/…
    $endgroup$
    – jschnei
    Jul 10 '17 at 0:52


















3












$begingroup$


I have to print numbers between two limits n and m, t times.



I created t variable that stores a number of test cases.



Outer for loop iterates for every test cases.



Inner for loop prints primes from m to n.



Code



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

int is_prime(int);

int main(void) {
int t, m, n;
scanf("%d", &t);
for (int i = 0; i < t; i++) {
scanf("%d %d", &m, &n);
for (int j = m; j <= n; j++) {
if (is_prime(j)) {
printf("%dn", j);
}
}
if (i < t - 1) printf("n");
}

return 0;
}

int is_prime(int num) {
if (num <= 1) return 0;
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) {
return 0;
}
}
return 1;
}


Problem: http://www.spoj.com/problems/PRIME1/



Can I have review?










share|improve this question









$endgroup$












  • $begingroup$
    You might be interested in a similar review I did a while back; a lot of the algorithmic notes there also apply here: codereview.stackexchange.com/questions/165576/…
    $endgroup$
    – jschnei
    Jul 10 '17 at 0:52














3












3








3





$begingroup$


I have to print numbers between two limits n and m, t times.



I created t variable that stores a number of test cases.



Outer for loop iterates for every test cases.



Inner for loop prints primes from m to n.



Code



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

int is_prime(int);

int main(void) {
int t, m, n;
scanf("%d", &t);
for (int i = 0; i < t; i++) {
scanf("%d %d", &m, &n);
for (int j = m; j <= n; j++) {
if (is_prime(j)) {
printf("%dn", j);
}
}
if (i < t - 1) printf("n");
}

return 0;
}

int is_prime(int num) {
if (num <= 1) return 0;
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) {
return 0;
}
}
return 1;
}


Problem: http://www.spoj.com/problems/PRIME1/



Can I have review?










share|improve this question









$endgroup$




I have to print numbers between two limits n and m, t times.



I created t variable that stores a number of test cases.



Outer for loop iterates for every test cases.



Inner for loop prints primes from m to n.



Code



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

int is_prime(int);

int main(void) {
int t, m, n;
scanf("%d", &t);
for (int i = 0; i < t; i++) {
scanf("%d %d", &m, &n);
for (int j = m; j <= n; j++) {
if (is_prime(j)) {
printf("%dn", j);
}
}
if (i < t - 1) printf("n");
}

return 0;
}

int is_prime(int num) {
if (num <= 1) return 0;
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) {
return 0;
}
}
return 1;
}


Problem: http://www.spoj.com/problems/PRIME1/



Can I have review?







algorithm c primes






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Jul 9 '17 at 16:24









java-develjava-devel

5301520




5301520












  • $begingroup$
    You might be interested in a similar review I did a while back; a lot of the algorithmic notes there also apply here: codereview.stackexchange.com/questions/165576/…
    $endgroup$
    – jschnei
    Jul 10 '17 at 0:52


















  • $begingroup$
    You might be interested in a similar review I did a while back; a lot of the algorithmic notes there also apply here: codereview.stackexchange.com/questions/165576/…
    $endgroup$
    – jschnei
    Jul 10 '17 at 0:52
















$begingroup$
You might be interested in a similar review I did a while back; a lot of the algorithmic notes there also apply here: codereview.stackexchange.com/questions/165576/…
$endgroup$
– jschnei
Jul 10 '17 at 0:52




$begingroup$
You might be interested in a similar review I did a while back; a lot of the algorithmic notes there also apply here: codereview.stackexchange.com/questions/165576/…
$endgroup$
– jschnei
Jul 10 '17 at 0:52










2 Answers
2






active

oldest

votes


















1












$begingroup$

The only even prime number is two, so with a little extra coding you can ignore even numbers in the for loop. For even more speed use a sieve, though maybe save that for when you get a 'TLE' failure.



A more formal code layout would be good as well, your if statements need expanding to include {...}. More vertical space (blank lines) a well as explanatory comments help. When you come back to your old code six months later you will thank yourself.



I prefer to set 0 and 1 as FALSE and TRUE to make code easier to read YMMV.



int is_prime(int num) {
if (num <= 1) {
return FALSE;
}

// Even numbers.
if (num % 2 == 0) {
return num == 2; // 2 is the only even prime.
}

// Odd numbers.
// Start loop at 3 and step 2 to skip even divisors.
for (int i = 3; i * i <= num; i += 2) {
if (num % i == 0) {
return FALSE;
}
}
return TRUE;
}





share|improve this answer









$endgroup$









  • 1




    $begingroup$
    Just include <stdbool.h> to avoid having to define it yourself, and get the lowercase versions at the same time.
    $endgroup$
    – Tamoghna Chowdhury
    Jul 10 '17 at 5:13










  • $begingroup$
    @TamoghnaChowdhury: Thanks. My C is very rusty.
    $endgroup$
    – rossum
    Jul 10 '17 at 7:49



















1












$begingroup$

Good that OP's code handles values <= 0, yet could have used is_prime(unsigned num) instead. Further: this is a good place for the only even prime detect.



Corner concern: The i * i <= num test fails for large num, like num = INT_MAX as i*i is always <= than INT_MAX or it is int overflow - which is undefined behavior (UB).



Preference: Use bool for return values that are either 0 or 1.



Many modern compilers/processors calculate the remainder and quotient for little/no additional cost. Use that as an exit condition.



bool is_prime(uintmax_t num) {
if (num <= 3) {
return num >= 2;
}
uintmax_t q = num;
for (uintmax_t i = 3; i <= q; i += 2) {
if (num % i == 0) {
return false;
}
q = num / i;
}
return num%2;
}


The next step in prime detection is use of the Sieve of Eratosthenes





Note for future: Code does not check the return value of scanf(). This is OK for test code, but not for code under test.






share|improve this answer











$endgroup$














    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "196"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f168768%2fprime-number-generator-in-c%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1












    $begingroup$

    The only even prime number is two, so with a little extra coding you can ignore even numbers in the for loop. For even more speed use a sieve, though maybe save that for when you get a 'TLE' failure.



    A more formal code layout would be good as well, your if statements need expanding to include {...}. More vertical space (blank lines) a well as explanatory comments help. When you come back to your old code six months later you will thank yourself.



    I prefer to set 0 and 1 as FALSE and TRUE to make code easier to read YMMV.



    int is_prime(int num) {
    if (num <= 1) {
    return FALSE;
    }

    // Even numbers.
    if (num % 2 == 0) {
    return num == 2; // 2 is the only even prime.
    }

    // Odd numbers.
    // Start loop at 3 and step 2 to skip even divisors.
    for (int i = 3; i * i <= num; i += 2) {
    if (num % i == 0) {
    return FALSE;
    }
    }
    return TRUE;
    }





    share|improve this answer









    $endgroup$









    • 1




      $begingroup$
      Just include <stdbool.h> to avoid having to define it yourself, and get the lowercase versions at the same time.
      $endgroup$
      – Tamoghna Chowdhury
      Jul 10 '17 at 5:13










    • $begingroup$
      @TamoghnaChowdhury: Thanks. My C is very rusty.
      $endgroup$
      – rossum
      Jul 10 '17 at 7:49
















    1












    $begingroup$

    The only even prime number is two, so with a little extra coding you can ignore even numbers in the for loop. For even more speed use a sieve, though maybe save that for when you get a 'TLE' failure.



    A more formal code layout would be good as well, your if statements need expanding to include {...}. More vertical space (blank lines) a well as explanatory comments help. When you come back to your old code six months later you will thank yourself.



    I prefer to set 0 and 1 as FALSE and TRUE to make code easier to read YMMV.



    int is_prime(int num) {
    if (num <= 1) {
    return FALSE;
    }

    // Even numbers.
    if (num % 2 == 0) {
    return num == 2; // 2 is the only even prime.
    }

    // Odd numbers.
    // Start loop at 3 and step 2 to skip even divisors.
    for (int i = 3; i * i <= num; i += 2) {
    if (num % i == 0) {
    return FALSE;
    }
    }
    return TRUE;
    }





    share|improve this answer









    $endgroup$









    • 1




      $begingroup$
      Just include <stdbool.h> to avoid having to define it yourself, and get the lowercase versions at the same time.
      $endgroup$
      – Tamoghna Chowdhury
      Jul 10 '17 at 5:13










    • $begingroup$
      @TamoghnaChowdhury: Thanks. My C is very rusty.
      $endgroup$
      – rossum
      Jul 10 '17 at 7:49














    1












    1








    1





    $begingroup$

    The only even prime number is two, so with a little extra coding you can ignore even numbers in the for loop. For even more speed use a sieve, though maybe save that for when you get a 'TLE' failure.



    A more formal code layout would be good as well, your if statements need expanding to include {...}. More vertical space (blank lines) a well as explanatory comments help. When you come back to your old code six months later you will thank yourself.



    I prefer to set 0 and 1 as FALSE and TRUE to make code easier to read YMMV.



    int is_prime(int num) {
    if (num <= 1) {
    return FALSE;
    }

    // Even numbers.
    if (num % 2 == 0) {
    return num == 2; // 2 is the only even prime.
    }

    // Odd numbers.
    // Start loop at 3 and step 2 to skip even divisors.
    for (int i = 3; i * i <= num; i += 2) {
    if (num % i == 0) {
    return FALSE;
    }
    }
    return TRUE;
    }





    share|improve this answer









    $endgroup$



    The only even prime number is two, so with a little extra coding you can ignore even numbers in the for loop. For even more speed use a sieve, though maybe save that for when you get a 'TLE' failure.



    A more formal code layout would be good as well, your if statements need expanding to include {...}. More vertical space (blank lines) a well as explanatory comments help. When you come back to your old code six months later you will thank yourself.



    I prefer to set 0 and 1 as FALSE and TRUE to make code easier to read YMMV.



    int is_prime(int num) {
    if (num <= 1) {
    return FALSE;
    }

    // Even numbers.
    if (num % 2 == 0) {
    return num == 2; // 2 is the only even prime.
    }

    // Odd numbers.
    // Start loop at 3 and step 2 to skip even divisors.
    for (int i = 3; i * i <= num; i += 2) {
    if (num % i == 0) {
    return FALSE;
    }
    }
    return TRUE;
    }






    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Jul 9 '17 at 22:16









    rossumrossum

    640411




    640411








    • 1




      $begingroup$
      Just include <stdbool.h> to avoid having to define it yourself, and get the lowercase versions at the same time.
      $endgroup$
      – Tamoghna Chowdhury
      Jul 10 '17 at 5:13










    • $begingroup$
      @TamoghnaChowdhury: Thanks. My C is very rusty.
      $endgroup$
      – rossum
      Jul 10 '17 at 7:49














    • 1




      $begingroup$
      Just include <stdbool.h> to avoid having to define it yourself, and get the lowercase versions at the same time.
      $endgroup$
      – Tamoghna Chowdhury
      Jul 10 '17 at 5:13










    • $begingroup$
      @TamoghnaChowdhury: Thanks. My C is very rusty.
      $endgroup$
      – rossum
      Jul 10 '17 at 7:49








    1




    1




    $begingroup$
    Just include <stdbool.h> to avoid having to define it yourself, and get the lowercase versions at the same time.
    $endgroup$
    – Tamoghna Chowdhury
    Jul 10 '17 at 5:13




    $begingroup$
    Just include <stdbool.h> to avoid having to define it yourself, and get the lowercase versions at the same time.
    $endgroup$
    – Tamoghna Chowdhury
    Jul 10 '17 at 5:13












    $begingroup$
    @TamoghnaChowdhury: Thanks. My C is very rusty.
    $endgroup$
    – rossum
    Jul 10 '17 at 7:49




    $begingroup$
    @TamoghnaChowdhury: Thanks. My C is very rusty.
    $endgroup$
    – rossum
    Jul 10 '17 at 7:49













    1












    $begingroup$

    Good that OP's code handles values <= 0, yet could have used is_prime(unsigned num) instead. Further: this is a good place for the only even prime detect.



    Corner concern: The i * i <= num test fails for large num, like num = INT_MAX as i*i is always <= than INT_MAX or it is int overflow - which is undefined behavior (UB).



    Preference: Use bool for return values that are either 0 or 1.



    Many modern compilers/processors calculate the remainder and quotient for little/no additional cost. Use that as an exit condition.



    bool is_prime(uintmax_t num) {
    if (num <= 3) {
    return num >= 2;
    }
    uintmax_t q = num;
    for (uintmax_t i = 3; i <= q; i += 2) {
    if (num % i == 0) {
    return false;
    }
    q = num / i;
    }
    return num%2;
    }


    The next step in prime detection is use of the Sieve of Eratosthenes





    Note for future: Code does not check the return value of scanf(). This is OK for test code, but not for code under test.






    share|improve this answer











    $endgroup$


















      1












      $begingroup$

      Good that OP's code handles values <= 0, yet could have used is_prime(unsigned num) instead. Further: this is a good place for the only even prime detect.



      Corner concern: The i * i <= num test fails for large num, like num = INT_MAX as i*i is always <= than INT_MAX or it is int overflow - which is undefined behavior (UB).



      Preference: Use bool for return values that are either 0 or 1.



      Many modern compilers/processors calculate the remainder and quotient for little/no additional cost. Use that as an exit condition.



      bool is_prime(uintmax_t num) {
      if (num <= 3) {
      return num >= 2;
      }
      uintmax_t q = num;
      for (uintmax_t i = 3; i <= q; i += 2) {
      if (num % i == 0) {
      return false;
      }
      q = num / i;
      }
      return num%2;
      }


      The next step in prime detection is use of the Sieve of Eratosthenes





      Note for future: Code does not check the return value of scanf(). This is OK for test code, but not for code under test.






      share|improve this answer











      $endgroup$
















        1












        1








        1





        $begingroup$

        Good that OP's code handles values <= 0, yet could have used is_prime(unsigned num) instead. Further: this is a good place for the only even prime detect.



        Corner concern: The i * i <= num test fails for large num, like num = INT_MAX as i*i is always <= than INT_MAX or it is int overflow - which is undefined behavior (UB).



        Preference: Use bool for return values that are either 0 or 1.



        Many modern compilers/processors calculate the remainder and quotient for little/no additional cost. Use that as an exit condition.



        bool is_prime(uintmax_t num) {
        if (num <= 3) {
        return num >= 2;
        }
        uintmax_t q = num;
        for (uintmax_t i = 3; i <= q; i += 2) {
        if (num % i == 0) {
        return false;
        }
        q = num / i;
        }
        return num%2;
        }


        The next step in prime detection is use of the Sieve of Eratosthenes





        Note for future: Code does not check the return value of scanf(). This is OK for test code, but not for code under test.






        share|improve this answer











        $endgroup$



        Good that OP's code handles values <= 0, yet could have used is_prime(unsigned num) instead. Further: this is a good place for the only even prime detect.



        Corner concern: The i * i <= num test fails for large num, like num = INT_MAX as i*i is always <= than INT_MAX or it is int overflow - which is undefined behavior (UB).



        Preference: Use bool for return values that are either 0 or 1.



        Many modern compilers/processors calculate the remainder and quotient for little/no additional cost. Use that as an exit condition.



        bool is_prime(uintmax_t num) {
        if (num <= 3) {
        return num >= 2;
        }
        uintmax_t q = num;
        for (uintmax_t i = 3; i <= q; i += 2) {
        if (num % i == 0) {
        return false;
        }
        q = num / i;
        }
        return num%2;
        }


        The next step in prime detection is use of the Sieve of Eratosthenes





        Note for future: Code does not check the return value of scanf(). This is OK for test code, but not for code under test.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited 16 mins ago

























        answered Jul 10 '17 at 2:51









        chuxchux

        13.6k21346




        13.6k21346






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Code Review Stack Exchange!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            Use MathJax to format equations. MathJax reference.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f168768%2fprime-number-generator-in-c%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Webac Holding Inhaltsverzeichnis Geschichte | Organisationsstruktur | Tochterfirmen |...

            What's the meaning of a knight fighting a snail in medieval book illustrations?What is the meaning of a glove...

            Salamanca Inhaltsverzeichnis Lage und Klima | Bevölkerungsentwicklung | Geschichte | Kultur und...