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

How can I make names more distinctive without making them longer?

Need a suitable toxic chemical for a murder plot in my novel

Would an alien lifeform be able to achieve space travel if lacking in vision?

Using "nakedly" instead of "with nothing on"

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

Cold is to Refrigerator as warm is to?

Stars Make Stars

If I can make up priors, why can't I make up posteriors?

Two different pronunciation of "понял"

Am I ethically obligated to go into work on an off day if the reason is sudden?

How to add zeros to reach same number of decimal places in tables?

If A makes B more likely then B makes A more likely"

Losing the Initialization Vector in Cipher Block Chaining

3 doors, three guards, one stone

Are my PIs rude or am I just being too sensitive?

Can a 1st-level character have an ability score above 18?

Autumning in love

Does the STL have a way to apply a function before calling less than?

What is the electric potential inside a point charge?

Was credit for the black hole image misattributed?

What to do with post with dry rot?

Is above average number of years spent on PhD considered a red flag in future academia or industry positions?

Fishing simulator

Estimate capacitor parameters



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 14 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

            名間水力發電廠 目录 沿革 設施 鄰近設施 註釋 外部連結 导航菜单23°50′10″N 120°42′41″E / 23.83611°N 120.71139°E / 23.83611; 120.7113923°50′10″N 120°42′41″E / 23.83611°N 120.71139°E / 23.83611; 120.71139計畫概要原始内容臺灣第一座BOT 模式開發的水力發電廠-名間水力電廠名間水力發電廠 水利署首件BOT案原始内容《小檔案》名間電廠 首座BOT水力發電廠原始内容名間電廠BOT - 經濟部水利署中區水資源局

            格濟夫卡 參考資料 导航菜单51°3′40″N 34°2′21″E / 51.06111°N 34.03917°E / 51.06111; 34.03917ГезівкаПогода в селі 编辑或修订