1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31







#17181  04/18/04 10:37 AM
c prime # generator

Joined: Apr 2004
Posts: 6
geodesic
Junior Member

Junior Member
Joined: Apr 2004
Posts: 6
The Riemann Manifold

hello. so far i have this program to generate the prime numbers (numbers whose only factors are 1 and themselves) between 1 and 100. what's wrong with this picture? #include <stdio.h>
main
{
int i,j,k,l=0;
for i=2; i<=20; ++i
{
for j=1; j<=i ; ++j
{
k = i%j;
if k == 0
{ l = ++l;
}
if l == 2
{printf "%d is a prime \n",i
}
}
}
return 0;
} thanks for the tips / suggestions G

Top



#17182  04/18/04 11:16 AM
Re: c prime # generator

Joined: Apr 2004
Posts: 6
geodesic
Junior Member

Junior Member
Joined: Apr 2004
Posts: 6
The Riemann Manifold

well i solved it in this manner #include <stdio.h>
int main(void)
{
int i,j,l=0;
while i <= 100
{
l = 0;
for j=1; j<=i; j++
{
if i%j == 0
{
l++;
}
}
if l == 2
{
printf "%d is a prime number\n" , i;
}
i++;
}
return 0;
} rather brutish etc. is there any way to stremline it .. like any way to use for loops instead of the while ... thanks G

Top



#17186  04/29/04 05:38 AM
Re: c prime # generator

Joined: Mar 2002
Posts: 256
ninjaneo
UGN Security Staff

UGN Security Staff
Joined: Mar 2002
Posts: 256
CA, USA

When I made my prime generator, I did it a different way...
If you take your range of numbers... lets say 20, starting with one. go like so...
Well, we know 1 is a prime. so skip that. 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20
(things that we've called primes are in bold, composites are in italics)
now, we will eliminate every multiple of 2.
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20
ok, now we see that three is the next prime (because its the next not elimanated number). So, lets kill multiples of 3.
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20
mmk, Most of those we already eliminated  but so what.
5 is next
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20
ok, well that didn't do much.
Well, now that its 11's turn and that is more than half of the range of numbers (20/2==10) there is no reason to check the rest.
Any noneliminated number is prime.
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20
hmmm... those italics didn't show up very well... oh well.

Top




Forums46
Topics45,531
Posts80,699
Members2,157

Most Online1,567 Apr 25th, 2010


0 registered members (),
6
guests and
2
spiders. 

