#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2013
    Location
    Johannesburg, South Africa
    Posts
    2
    Rep Power
    0

    Talking Need some help, please


    Hi guys,

    I am busy learning C on my MacBook through xCode as the DE.

    The reason I am doing it this way is due to also going into iOS development. So, to be a better iOS developer, I want to make sure I understand the C language better too, as well as Objective-C. :D

    I have started reading the book: Learn C on Mac (4th edition) by David Mark's, I think.

    Now, the following bit of code I am having issues with - I understand how this code works 99% - the challenge in the code is to make the program compute prime numbers 1 to 100.

    I have having difficulty figuring out how / where to implement a for / while loop to count to 100 (candidate is the int I need to get from 1 to 100)

    Code:
    #include <stdio.h>
    #include <math.h> //used for extra math functions
    #include <stdbool.h> // Used for the definition of truth
    
    int main(int argc, const char * argv[])
    {
        bool isPrime;
        int startingPoint, candidate, last, i;
        
        startingPoint = 1;
        
        if ( startingPoint < 2){
            candidate = 2;
        }
        else if ( startingPoint == 2 ) {
            candidate = 3;
        }
        else {
            candidate = startingPoint;
            if (candidate % 2 == 0 ) /*Test only odd numbers */
                candidate --;
            do {
                isPrime = true;
                candidate +=2;
                last = sqrt( candidate );
                
                for (i =3; (i <= last) && isPrime ;i +=2 ) {
                    if ( (candidate % i) == 0)
                        isPrime = false;
                }
            }while ( ! isPrime );
            
            printf ( "The next prime number afer: %d is %d, Happy?" , startingPoint, candidate); 
             return 0;
    }
    }
    After trying a few methods, I am stuck.

    Can anyone help a newbie to C out and show me how this is done?

    Also, if you can explain a little and not just provide the code, that would be great!

    Thanks guys!
  2. #2
  3. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,704
    Rep Power
    480
    Even a dude like me can follow this program.
    Code:
        startingPoint = 1;
        
        if ( startingPoint < 2){
            candidate = 2;
        }
    startingPoint is assigned 1.
    1 is less than 2.
    candidate is assigned 2.

    And that's all that happens in your program. Let's fix it.
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <math.h> //used for extra math functions
    #include <stdbool.h> // Used for the definition of truth   WOW!
    
    int main(int argc, const char * argv[]) {
      int
        j,k,			/* secret */
        i,				/* index into primes */
        isPrime,
        maximum,
        candidate,
        primes_found = 0,	/* mark the range of valid entries in primes*/
        primes[50];	/* there are potentially 50 primes, the odd numbers greater than 1, and 2. */
    
      primes[primes_found++] = 2; /* 2 is a prime number, odd because it's even. */
    
      for (candidate = 3; candidate < 101; candidate += 2) { /* for loop iterating over odd numbers */
    
        fprintf(stderr, "\ttesting %d", candidate);	/* show diagnostic information on stderr */
    
        maximum = 2 + (int)sqrt(candidate);	/* need to test divisors only through sqrt(candidate) */
    
        isPrime = true;
    
        for (i = 1; (i < primes_found) && (primes[i] < maximum); ++i)
          /*
    	start i at 1 because we already handled even numbers.
    	(i < primes_found) because these are the only valid entries in primes array
    	(primes[i] < maximum) because, you already understand why.  Considering magnitude,
    	the product of two factors greater than the square root of a number exceeds the number.
          */
    
          if ((candidate % primes[i]) == 0) {
    	isPrime = false;
    	fprintf(stderr, "\t%d is a factor.", primes[i]); /* more of these exciting diagnostics */
    	break;						 /* stop testing.  We know the answer */
          }
    
        if (isPrime)
          primes[primes_found++] = candidate;
    
        fputc('\n', stderr);	/* keep the diagnostics pretty */
      }
    
      /* do something with these primes.  Show 'em */
      printf("Found %d primes less than 101.  They are:\n\n", primes_found);
      k = primes_found / 5 + (! ! (primes_found % 5));
      for (j = 0; j < k; ++j) {
        for (i = j; i < primes_found; i += k)
          printf("%4d",primes[i]);
        putchar('\n');
      }
    
      return EXIT_SUCCESS;
    }
    [code]Code tags[/code] are essential for python code and Makefiles!
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2013
    Location
    Johannesburg, South Africa
    Posts
    2
    Rep Power
    0
    Thanks for your input.

    Actually, the program outputs 5 and the answer. Not 2.

    I did manage to fix the program to give me the intended results I want.

    Here is the modified version:

    Code:
    //
    //  main.c
    //  nextPrime
    //
    //  Created by Robert Clegg on 5/8/13.
    //  Copyright (c) 2013 com.bignerdranch. All rights reserved.
    //
    
    #include <stdio.h>
    #include <math.h> //used for extra math functions
    #include <stdbool.h> // Used for the definition of truth
    
    int main(int argc, const char * argv[])
    {
        bool isPrime;
        int startingPoint, candidate, last, i;
        
        for (startingPoint = 0; startingPoint < 100; ++startingPoint){
    
        
        if ( startingPoint < 2){
            candidate = 2;
        }
        else if ( startingPoint == 2 ) {
            candidate = 3;
        }
        else {
            candidate = startingPoint;
            
            
            if (candidate % 2 == 0 ) /*Test only odd numbers */
                candidate --;
            do {
                isPrime = true;
                candidate +=2;
                last = sqrt( candidate );
                          for (i = 3; (i <= last) && isPrime ;i +=2 )
                          {
                                  if ( (candidate % i) == 0)
                        isPrime = false;
                                                        }
                
            }
            while ( ! isPrime );
            
            printf ( "The next prime number afer: %d is %d, Happy?\n" , startingPoint, candidate);
        }
        
        }
         return 0;
    }
    My main problem was due to terminating the for loop prematurely and having the for loop inside the else statement.

    This modified bit of code now prints the next prime numbers from 1 to 100, to the console.
  6. #4
  7. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,704
    Rep Power
    480
    What compiler do you use? The program of your first post has no output except for the undefined status code, exactly as I expected.
    [code]Code tags[/code] are essential for python code and Makefiles!

IMN logo majestic logo threadwatch logo seochat tools logo