Thread: could I got some help to edit this code please

  1. #1
    Registered User
    Join Date
    Aug 2009
    Posts
    3

    Smile could I got some help to edit this code please

    Hey guys, my name is JUSTIN and this is my first thread here

    I want to edit Fibonacci program which do this equation
    Fib(n) = 1 if n is 0 or 1
    =Fib(n-1) + Fib(n-2) otherwise


    and make it work for this one:
    f(n) = 1 if n=1,2,3
    = f(n-1)*f(n-2)+f(n-3), when n>3

    the code is attached and its here also:

    Code:
    /* fibonacci  program   written by ian a. mason @ u.n.e easter '97 */
    /* touched up easter '98                                           */ 
    /* and again march '99                                             */
    /* and again august  '01                                           */
    /* and again august  '02                                           */
    /* and again august  '04                                           */
    #include <stdio.h>     /* for fprintf  */
    #include <stdlib.h>    /* for exit     */
    #include <unistd.h>    /* for fork     */
    #include <string.h>    /* for strtok   */
    #define BUFFSIZE 50
    int parse_args(int argc,  char *argv[ ], int *np){
      if ( (argc != 2) || ((*np = atoi (argv[1])) <= 0) ) {
        fprintf (stderr, "Usage: %s nprocs\n", argv[0]);
        return(-1); };
      return(0); 
    }
    int make_trivial_ring(){   
      int   fd[2];
      if (pipe (fd) == -1) 
        return(-1); 
      if ((dup2(fd[0], STDIN_FILENO) == -1) ||
          (dup2(fd[1], STDOUT_FILENO) == -1)) 
        return(-2); 
      if ((close(fd[0]) == -1) || (close(fd[1]) == -1))   
        return(-3); 
      return(0); 
    }
    int add_new_node(int *pid){
      int fd[2];
      if (pipe(fd) == -1) 
        return(-1); 
      if ((*pid = fork()) == -1)
        return(-2); 
      if(*pid > 0 && dup2(fd[1], STDOUT_FILENO) < 0)
        return(-3); 
      if (*pid == 0 && dup2(fd[0], STDIN_FILENO) < 0)
        return(-4); 
      if ((close(fd[0]) == -1) || (close(fd[1]) == -1)) 
        return(-5);
      return(0);
    }
    void get_integers(char buff[], long *first, long *second){
      char* token = NULL;
      if((first == NULL) || (second == NULL)) return;
      if(read(STDIN_FILENO, buff, BUFFSIZE) > 0){
        *first  = atol((((token = strtok(buff," ")) == NULL) ? "0" : token));
        *second = atol((((token = strtok(NULL," ")) == NULL) ? "0" : token)); 
      } else {
        *first = 0;
        *second = 0;
      }
    }
    void safe_sum(long first, long *second, long *third){
      if((second == NULL) || third == NULL) return;
      *third = first + *second;
      if(*third < 0){
        fprintf(stderr, 
                "Overflow detected: %ld + %ld != %ld\n",
                first, *second, *third);
        *third   = 0;
        *second  = 0; };
    }
    int send_numbers(char buff[], long num1, long num2){
      int bytes, len;
      sprintf(buff, "%ld %ld", num1, num2);
      len = strlen(buff) + 1;
      if((bytes = write(STDOUT_FILENO, buff, len)) != len){
        fprintf(stderr, 
                "Write of %d bytes failed, only sent %d bytes\n",
                len, bytes);
        return -1; 
      } else {
        return bytes;
      }
    }
    
    void report_sum(int i, long first, long old_second, long second, long third){
      fprintf(stderr,
              "\nProcess %d with PID %d and parent PID %d recieved %ld %ld and sent %ld %ld.\n",
              i, (int)getpid(), (int)getppid(), first, old_second, second, third); 
    }
    int main(int argc,  char *argv[]){
       int    i;               /* number of this process (starting with 1)   */
       int    childpid;        /* indicates process should spawn another     */ 
       int    nprocs;          /* total number of processes in ring          */ 
       char   buff[BUFFSIZE];  /* string for integers                        */
       long   first;           /* first integer in fibonacci computation     */
       long   second;          /* second integer in fibonacci computation    */
       long   third ;          /* sum of first and second                    */
       if(parse_args(argc,argv,&nprocs) < 0) exit(EXIT_FAILURE);
       if(make_trivial_ring() < 0){
         perror("Could not make trivial ring");
         exit(EXIT_FAILURE); };
       for (i = 1; i < nprocs;  i++) {
         if(add_new_node(&childpid) < 0){
           perror("Could not add new node to ring");
           exit(EXIT_FAILURE); };
         if (childpid) break; };
       {
         /* ring process code  */     
         long old_second;
         if(i == 1){
           /* mother of all processes */
           send_numbers(buff, 1,1); }
         /* all processes     */
         get_integers(buff, &first, &second);
         old_second = second;
         safe_sum(first,&second,&third);
         if(i > 1){ 
           send_numbers(buff, second, third);
           report_sum( i, first, old_second, second, third); }
         else {
           fprintf(stderr,"\n\nfibonacci(%d) = %ld\n\n", nprocs, second); }
         exit(EXIT_SUCCESS); 
       }
    }     /* end of main program here */

    cheeers

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    I suggest that you try writing the program from scratch.

    EDIT:
    On second thought, you might want to state what you have tried.
    Last edited by laserlight; 08-25-2009 at 09:19 AM.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by J U S T I N View Post
    I want to edit Fibonacci program which do this equation

    and make it work for this one:
    You will have to explain why you would want to use that code for anything. I know a couple of ways to produce the Fibronacci sequence (recursive and iterative), but neither of those requires more than a few lines of code.

    I am not sure why someone wrote that, AFAICT it is far from efficient also. If there is a competition for "worst fibronacci program ever", I think it may have a good chance of winning...
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  4. #4
    Registered User
    Join Date
    Sep 2004
    Location
    California
    Posts
    3,268
    If there is a competition for "worst fibronacci program ever", I think it may have a good chance of winning...
    I don't see what's wrong with it. Obviously the goal was not write a fibonacci algorithm in as few lines as possible. It appears that the goal is to distribute the algorithm among several processes. In other words, it's more of an exercise in process management than anything else. At any rate, I don't see why you consider it to be the "worst" ever.
    bit∙hub [bit-huhb] n. A source and destination for information.

  5. #5
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300

    Cool

    Quote Originally Posted by bithub View Post
    I don't see what's wrong with it. Obviously the goal was not write a fibonacci algorithm in as few lines as possible. It appears that the goal is to distribute the algorithm among several processes. In other words, it's more of an exercise in process management than anything else. At any rate, I don't see why you consider it to be the "worst" ever.
    Okay, fair enough, but the OP does not -- at least at present -- appear to be asking about process management. I completely agree that it was probably intended to be an exercise/demonstration/experiment about fork(), IPC, etc, using a very simple premise (the fib sequence). Which is to say it is the kind of program where "what it does" is sort of irrelevant, it is more "how it does it" that a reasonable person would find potentially interesting*.

    By "worst", I meant that this will probably take twice or ten times as long to compute the sequence as a conventional method. Ie, it is not a good way to accomplish the goal. By "win the contest", I meant that if it works (presumably it does) it would represent a very unorthodox approach. Like racing bathtubs. Nobody will give you an award for the bathtub as a boat, but you could still have the craziest bathtub boat ever. Is what I was trying to say. No offence to "ian a. mason", at all.

    * even considering that, I don't think the code is worth adopting (nor was it intended to be) for the purposes of doing some other process management or IPC stuff. Like you might find the syntax examples useful, etc. but it is an oddball demo, not some kind of modular, re-usable model. IMO.
    Last edited by MK27; 08-25-2009 at 12:50 PM.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  6. #6
    Registered User
    Join Date
    Aug 2009
    Posts
    3
    Quote Originally Posted by bithub View Post
    It appears that the goal is to distribute the algorithm among several processes. In other words, it's more of an exercise in process management than anything else.

    thank u bithub, the idea about this complected code is not to do the equation, its to manage the child process and to practice the rings "token rings" in C. Moreover, it has all the FAILURE messages which help to control the program. the problem for me is I couldn't point to the part of the program that makes this equation, coz it has many function and everyone communicate with a another so it seems to me not easy .

  7. #7
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    Quote Originally Posted by J U S T I N View Post
    the problem for me is I couldn't point to the part of the program that makes this equation, coz it has many function and everyone communicate with a another so it seems to me not easy .
    If I counted correctly, there are only three plus signs in the entire program, with one of them in a string literal error message, and I would bet that the one of them that is in the form variable = variable + variable is the one you're looking for.

  8. #8
    Registered User
    Join Date
    Aug 2009
    Posts
    3
    ok, I'll show u my work till now

    I added "fourth" value and I left the "third" for the result
    but stil not working

    Code:
    /* fibonacci  program   written by ian a. mason @ u.n.e easter '97 */
    /* touched up easter '98                                           */ 
    /* and again march '99                                             */
    /* and again august  '01                                           */
    /* and again august  '02                                           */
    /* and again august  '04                                           */
    #include <stdio.h>     /* for fprintf  */
    #include <stdlib.h>    /* for exit     */
    #include <unistd.h>    /* for fork     */
    #include <string.h>    /* for strtok   */
    #define BUFFSIZE 50
    int parse_args(int argc,  char *argv[ ], int *np){
      if ( (argc != 2) || ((*np = atoi (argv[1])) <= 0) ) {
        fprintf (stderr, "Usage: %s nprocs\n", argv[0]);
        return(-1); };
      return(0); 
    }
    int make_trivial_ring(){   
      int   fd[2];
      if (pipe (fd) == -1) 
        return(-1); 
      if ((dup2(fd[0], STDIN_FILENO) == -1) ||
          (dup2(fd[1], STDOUT_FILENO) == -1)) 
        return(-2); 
      if ((close(fd[0]) == -1) || (close(fd[1]) == -1))   
        return(-3); 
      return(0); 
    }
    int add_new_node(int *pid){
      int fd[2];
      if (pipe(fd) == -1) 
        return(-1); 
      if ((*pid = fork()) == -1)
        return(-2); 
      if(*pid > 0 && dup2(fd[1], STDOUT_FILENO) < 0)
        return(-3); 
      if (*pid == 0 && dup2(fd[0], STDIN_FILENO) < 0)
        return(-4); 
      if ((close(fd[0]) == -1) || (close(fd[1]) == -1)) 
        return(-5);
      return(0);
    }
    void get_integers(char buff[], long *first, long *second, long *fourth){
      char* token = NULL;
      if((first == NULL) || (second == NULL) || (fourth == NULL )) return;
      if(read(STDIN_FILENO, buff, BUFFSIZE) > 0){
        *first  = atol((((token = strtok(buff," ")) == NULL) ? "0" : token));
        *second = atol((((token = strtok(NULL," ")) == NULL) ? "0" : token));
        *fourth = atol((((token = strtok(NULL," ")) == NULL) ? "0" : token)); 
      } else {
        *first = 0;
        *second = 0;
        *fourth = 0;
      }
    }
    void safe_sum(long first, long *second, long *third, long *fourth){
      if((second == NULL) || third == NULL || fourth == NULL ) return;
      *third = first * *second + *fourth;
      if(*third < 0){
        fprintf(stderr, 
                "Overflow detected: %ld * %ld + %ld!= %ld\n",
                first, *second, *fourth, *third);
        *third   = 0;
        *second  = 0;
        *fourth = 0; };
    }
    int send_numbers(char buff[], long num1, long num2, long num3){
      int bytes, len;
      sprintf(buff, "%ld %ld %ld", num1, num2, num3);
      len = strlen(buff) + 1;
      if((bytes = write(STDOUT_FILENO, buff, len)) != len){
        fprintf(stderr, 
                "Write of %d bytes failed, only sent %d bytes\n",
                len, bytes);
        return -1; 
      } else {
        return bytes;
      }
    }
    
    void report_sum(int i, long first, long old_second, long second, long third, long fourth){
      fprintf(stderr,
              "\nProcess %d with PID %d and parent PID %d recieved %ld %ld and sent %ld %ld %ld.\n",
              i, (int)getpid(), (int)getppid(), first, old_second, second, third, fourth); 
    }
    int main(int argc,  char *argv[]){
       int    i;               /* number of this process (starting with 1)   */
       int    childpid;        /* indicates process should spawn another     */ 
       int    nprocs;          /* total number of processes in ring          */ 
       char   buff[BUFFSIZE];  /* string for integers                        */
       long   first;           /* first integer in fibonacci computation     */
       long   second;          /* second integer in fibonacci computation    */
       long   third ;          /* sum of first and second                    */
       long	  fourth;
       if(parse_args(argc,argv,&nprocs) < 1) exit(EXIT_FAILURE); //I changed the zero to one
          if(make_trivial_ring() < 1){							//I changed the zero to one
         perror("Could not make trivial ring");
         exit(EXIT_FAILURE); };
       for (i = 1; i < nprocs;  i++) {
         if(add_new_node(&childpid) < 1){						//I changed the zero to one
           perror("Could not add new node to ring");
           exit(EXIT_FAILURE); };
         if (childpid) break; };
       {
         /* ring process code  */     
         long old_second;
         if(i == 1 /*|| i == 2 || i = 3 */   ){
           /* mother of all processes */
           send_numbers(buff, 1,1,1); }		//whats going on here ? 
         /* all processes     */
         get_integers(buff, &first, &second, &fourth);
         old_second = second;
         safe_sum(first,&second,&third,&fourth);
         if(i > 3){ 									//I changed the 1 to 3
                send_numbers(buff, second, third, fourth);
           report_sum( i, first, old_second, second, third, fourth); }
         else {
           fprintf(stderr,"\n\nfibonacci(%d) = %ld\n\n", nprocs, second); }
         exit(EXIT_SUCCESS); 
       }
    }     /* end of main program here */

  9. #9
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    Why did you change all the zeroes to one? For instance, add_new_node will always return less than one.

    You should also check that the "movement" happens correctly (i.e., for whatever reason, you have first, second, fourth, third, so the next time through it should be second, fourth, third, result).

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Enforcing Machine Code Restrictions?
    By SMurf in forum Tech Board
    Replies: 21
    Last Post: 03-30-2009, 07:34 AM
  2. edit control text buffer
    By scurvydog in forum Windows Programming
    Replies: 4
    Last Post: 12-11-2008, 10:13 AM
  3. Can you create, edit and compile C code with a C++ IDE?
    By nerdpirate in forum C Programming
    Replies: 4
    Last Post: 05-31-2008, 01:54 AM
  4. Problem : Threads WILL NOT DIE!!
    By hanhao in forum C++ Programming
    Replies: 2
    Last Post: 04-16-2004, 01:37 PM