Prime numbers..problem with code

zeeshan's Avatar, Join Date: Dec 2006
Newbie Member
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 shabbir; 4Dec2006 at 10:45.. Reason: Code formating.
0
pradeep's Avatar, Join Date: Apr 2005
Team Leader
Here is the code for finding a prime number in a specified range.

Code: C
#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
0
friendsforniraj's Avatar, Join Date: Nov 2006
Go4Expert Member
thats great now