TIP: Click on subject to list as thread! ANSI
echo: c_echo
to: John Metcalf
from: George White
date: 1998-08-08 11:38:02
subject: Prime Numbers Problem

Hi John,

You asked:

JM>I can't program in C, I prefer various types of asm, but I have
JM>had a go at writing a C program to generate prime numbers...

JM>#include "stdio.h"
JM>#define m 100
JM>main() {int i=1,j,p=1,fl,l[m]; while (pwhile (jif (fl) {l[p++]=i; printf("%d\n", i);} } }

JM>Okay, here's the problem :-) - it compiles okay using a couple of
JM>freeware compilers, and prints out the primes nicely. However, when
JM>I compiled it on a Vax, using a 'real' compiler,it just printed out
JM>a list of odd numbers...

Typical...

JM>I can't see what the problem is. I have a suspicion it is something
JM>to do with the handling of FL. Can anyone help me here...

No, it isn't really. It's an initialisation problem with p and l[]. You
initialise p to 1, so there is never any value stored in l[0], but
the first time through for a number (with j = 0) you test for
termination of the while on "l[0] * l[0] <= i". If l[0] has a random
value left in it (as it commonly will) you will fail on the first while
without ever reaching the testing for dividors, so all tested values
will be printed.

My suggested changes (with comments).
I expanded it to make it more readable.

#include "stdio.h"

#define m 100

/* For ANSI C I prefer to be explicit and use */
int main (void)
{
unsigned int i = 1,j,p = 0,fl,l[m] = {3,5};
/* Initialise p = 0, not 1 */
/* Initialise l[] with the first known primes expected */
while (p < m)
  {
  i += 2;
  fl = 1;
  j = 0;
/* You had this test. */
/*  while (j < p && fl && l[j] * l[j] <= i) */
/* By using a break when fl is cleared you can simplify the test to */
  while (j < p && l[j] * l[j] <= i)
/* which should be quicker */
    if (i % l[j++] == 0)
      {
      fl = 0;
      break;
      }
  if (fl)
    {
    l[p++] = i;
    printf ("%u\n", i);
    }
  }
/* We need a return value from main() */
return 0;
}

George

 * SLMR 2.1a * Computers eliminate spare time.

--- Maximus/2 3.01
* Origin: DoNoR/2,Woking UK (44-1483-717904) (2:440/4)
SEEN-BY: 396/1 622/419 632/371 633/260 267 270 371 634/397 635/506 728 810
SEEN-BY: 639/252 670/213 218
@PATH: 440/4 255/1 251/25 2320/38 270/101 396/1 633/260 635/506 728 633/267

SOURCE: echomail via fidonet.ozzmosis.com

Email questions or comments to sysop@ipingthereforeiam.com
All parts of this website painstakingly hand-crafted in the U.S.A.!
IPTIA BBS/MUD/Terminal/Game Server List, © 2025 IPTIA Consulting™.