Prime numbers..problem with code

Discussion in 'C' started by zeeshan, Dec 1, 2006.

  1. zeeshan

    zeeshan New Member

    Joined:
    Dec 1, 2006
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    Location:
    Karachi .Pakistan
    hi friends, im a newbie at C,

    im trying to code for a program which cud return all prime numbers in a specific range.

    its returning the results with an error, which is , it also includes the products of two prime numbers in results,
    for example 15=3*5 and 21=3*7

    my code is
    ---------------------------------------------------------
    Code:
    #include<conio.h>
    #include<stdio.h>
    void main()
    {
    clrscr();
    for (int i=1;i<=300;i++)
     {
      for(int j=2;j<=i;j++)
       if(i%j==0 )
    
       break;
       else
           {
    	printf("\t%d ",i);
    	break;
    	}
      }
    getche();
    }
    --------------------------------------------------
    Result:

    3 5 7 9 11 13 15 17 19 21 23 .................

    kindly guide me where the problem resides.
    which is letting 15,21 etc in output.
     
    Last edited by a moderator: Dec 4, 2006
  2. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,645
    Likes Received:
    87
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    http://blog.pradeep.net.in
    Here is the code for finding a prime number in a specified range.

    Code:
    #include <stdio.h>
    #include <math.h>
    // The range of numbers where you want to look for prime numbers
    #define RANGE_MIN 2
    #define RANGE_MAX 100
    
    void main(void)
    {
        int i,j,sq,is_prime;
    
        for(i=RANGE_MIN;i<=RANGE_MAX;i++)
        {
    
            is_prime = 1;
            sq = sqrt(i); // calculate the square root
            for(j=2;j<=sq;j++)
            {
                if(i%j==0)
                    is_prime = 0;
            }
    
            if(is_prime)
                printf("%d, ",i);
        }
    }
    Also checkout this thread http://www.go4expert.com/showthread.php?t=2049
     
  3. friendsforniraj

    friendsforniraj New Member

    Joined:
    Nov 24, 2006
    Messages:
    40
    Likes Received:
    0
    Trophy Points:
    0
    Occupation:
    studying
    thats great now
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice