# prime numbers

Page 1 of 1

## 1 Replies - 673 Views - Last Post: 13 November 2008 - 07:57 AMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=71724&amp;s=b63cfb78c54b9b4e7d01a9086b396f28&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 munnap

Reputation: 0
• Posts: 2
• Joined: 13-November 08

# prime numbers

Posted 13 November 2008 - 07:12 AM

hi!
i wanted to write a program to print the first n rime numbers using the following code..
#include<stdio.h>
main()
{
int n,i,f=0;
printf("enter a number");
scanf("%d",&n);
for(;n>0;n--)
{
for(i=1;i<n;i++)
{
if(n%i==0)
{
f++;
}
}
if(f==2)
printf"\n%d",n);
}
}

is there anything wrong with dis? coz when ever i give any number the window gets inactive if it is not prime and if a prime the number which i gave gets printed!
plz help me!

Is This A Good Question/Topic? 0

## Replies To: prime numbers

### #2 AmitTheInfinity

• C Surfing ∞

Reputation: 119
• Posts: 1,565
• Joined: 25-January 07

## Re: prime numbers

Posted 13 November 2008 - 07:57 AM

```for(;n>0;n--)
{
for(i=2;i<n;i++) // every number is divisible by 1 so start with 2. and you can have loop running till n/2 as well.
//I think it will work and will save few iterations too.
{
if(n%i==0)
{
break;
}
}

if(i==n)
printf"\n%d",n);
}

```

I wrote it on the fly and hence it might have some small mistakes... please watch out for them.

Page 1 of 1

 .related ul{list-style-type:circle;font-size:12px;font-weight:bold;}.related li{margin-bottom:5px;background-position:left 7px!important;margin-left:-35px;}.related h2{font-size:18px;font-weight:bold;}.related a{color:blue;}