1 Replies - 559 Views - Last Post: 13 November 2008 - 07:57 AM Rate Topic: -----

#1 munnap  Icon User is offline

  • New D.I.C Head

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

prime numbers

Post icon  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  Icon User is offline

  • C Surfing ∞
  • member icon

Reputation: 109
  • View blog
  • Posts: 1,530
  • 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.

I hope this will help you. :)
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1