Eat. Sleep. Code: The Computer Programming Thread, Ver. 010

Hmm, I don’t know why but now it says



"Project3ver4.c", line 11: function designator is not of function type
"Project3ver4.c", line 11: warning: improper pointer/integer combination: op "="
cc: acomp failed for Project3ver4.c

Anyway here’s the program I tried to run.


#include <stdio.h>
int isperfect (int x);
int main()
{
  int i, j, isperfect;

  printf( "" );

  for(i = 2; i <= 10000; i++)
  {
      isperfect = isperfect(i);
      if (isperfect == 1)
      {
        printf("%d = 1", i);
        for(j = 1; j*j < i; j++)
        {
           if(i%j == 0)
             printf("%d", j);
        }
        printf("
");
      }
  }
return 0;
}

int isperfect( int x)
{
  int i, sum =0;

  for(i=1 ; i*i<x ; i++)
  {
      if( x%i == 0 )
      sum += i;
  }
if(sum == x)
 return 1;
else
 return 0;
}


Anyway even if we resolve the line 11 problem, there’s still the “undefined” problem to look out for as well since after doing some reading in my textbook, it the undefined problem means that while the program’s syntax is correct, the program ran into an error in the linking stage.

It could be your compiler doesn’t like variable and functions to have the same name, try changing the variable isperfect to something else

Like have the value of isperfect equal to a letter variable, is that what you mean?

ie: “k = isperfect(i)”

Made a few revisions to a previous version and it started working for some reason, but I’m not complaining. :rofl:



#include <stdio.h>
int isperfect (int x);
int main()
{
    int y, z;

    printf( "" );

    for( z=2; z<=10000; z++ )
    {
        y = isperfect(z);
        if (y == 1)
        {
            printf( "%d
",z );
        }
    }
    return 0;
}
int isperfect( int x)
{
    int i,sum =0;

    for( i=1 ; i<x ; i++)
    {
      if( x%i == 0 )
      sum += i;
    }
    if ( sum == x )
    return 1;
    else
    return 0;
}

And the output…


6
28
496
8128

Now when I tried to make it produce the desired output with this newly revised program…



include <stdio.h>
int isperfect (int x);
int main()
{
    int y, z;

    printf( "" );

    for( z=2; z<=10000; z++ )
    {
        y = isperfect(z);
        if (y == 1)
        {
         printf( "6 = 1 + 2 + 3
" );
         printf( "28 = 1 + 2 + 4 + 7 + 14
" );
         printf( "496 = 1 + 2 + 4 + 8 + 16 + 31 + 62 + 124 + 248
" );
         printf( "8128 = 1 + 2 + 4 + 8 + 16 + 32 + 64 + 127 + ");
         printf( "254 + 508 + 1016 + 2032 + 4064
");       
        }
    }
    return 0;
}
int isperfect( int x)
{
    int i,sum =0;

    for( i=1 ; i<x ; i++)
    {
       if( x%i == 0 )
       sum += i;
    }
    if ( sum == x )
     return 1;
    else
     return 0;
}

I get this…



6 = 1 + 2 + 3
28 = 1 + 2 + 4 + 7 + 14
496 = 1 + 2 + 4 + 8 + 16 + 31 + 62 + 124 + 248
8128 = 1 + 2 + 4 + 8 + 16 + 32 + 64 + 127 + 254 + 508 + 1016 + 2032 + 4064
6 = 1 + 2 + 3
28 = 1 + 2 + 4 + 7 + 14
496 = 1 + 2 + 4 + 8 + 16 + 31 + 62 + 124 + 248
8128 = 1 + 2 + 4 + 8 + 16 + 32 + 64 + 127 + 254 + 508 + 1016 + 2032 + 4064
6 = 1 + 2 + 3
28 = 1 + 2 + 4 + 7 + 14
496 = 1 + 2 + 4 + 8 + 16 + 31 + 62 + 124 + 248
8128 = 1 + 2 + 4 + 8 + 16 + 32 + 64 + 127 + 254 + 508 + 1016 + 2032 + 4064
6 = 1 + 2 + 3
28 = 1 + 2 + 4 + 7 + 14
496 = 1 + 2 + 4 + 8 + 16 + 31 + 62 + 124 + 248
8128 = 1 + 2 + 4 + 8 + 16 + 32 + 64 + 127 + 254 + 508 + 1016 + 2032 + 4064


Hahaha, what a screw up! :rofl:

Anyway I’m getting closer, any ideas guys?

firstly, you can’t hardcode the output like that. You’ll not pass the assignment. I think it worked because you got rid of the isperfect variable; the variable and the function both had the same name, so it didn’t work. rename the variable isperfect to something else and leave the function named isperfect. Then use the logic in my output loop. If you really can’t see why your program output like it did, then I’m not sure what else to say haha

Is there any reason to learn C over C++ besides saying that you can know C?

C forces you to practice memory management at a much more literal level than C++. Good for paranoia when learning computer architecture and other computer science analysis and implementation of algorithms.

Once you’ve gotten C down, there is no reason to not just use C++, STL, and everything else.

When one uses g++ to compile, the C++ standard does not suffer from some of the setbacks of not being up to date with the current C version. Originally C++ was using out-dated C, but they’ve mostly fixed that now, so who cares?!

Learning C also lets you branch off into something other than C++, such as C#, more easily.
Some architectures require C as opposed to C++, for instance embedded systems.
A lot of good stuff is written in C and will have complications and subtleties with C++ if you want to work with it.

Hahaha, yeah I was just fucking around. I did that on my first homework and the professor was baffled at how much typing I had to do. I can show it to you guys at some other time, I think you guys will find it funny. Anyway I tweaked it a bit some more and this is what I got now.



#include <stdio.h>
int isperfect (int x);
int main()
{
  int a, b, c;

  printf( "" );

  for( a=2; a<=10000; a++ )
  {
      b = isperfect(a);
      if (b == 1)
        {
            printf("%d = ", a);
            for(c = 1; c < a; c++)
            {
              if(a%c == 0)
              printf("%d +", c);
            }
            printf("
");
        }
  }
  return 0;
}
int isperfect( int x)
{
  int i, sum =0;

  for( i=1; i<x ; i++)
  {
      if( x%i == 0 )
      sum += i;
  }
  if ( sum == x )
    return 1;
  else
    return 0;
}

And got…



6 = 1 + 2 + 3 +
28 = 1 + 2 + 4 + 7 + 14 +
496 = 1 + 2 + 4 + 8 + 16 + 31 + 62 + 124 + 248 +
8128 = 1 + 2 + 4 + 8 + 16 + 32 + 64 + 127 + 254 + 508 + 1016 + 2032 + 4064 +


Now to remove that pesky + sign at the very end.

EDIT: Tweaked ONE MORE TIME…



#include <stdio.h>
int isperfect (int x);
int main()
{
   int a, b, c;

   printf( "" );

   for( a=2; a<=10000; a++ )
   {
      b = isperfect(a);
      if (b == 1)
         {
            printf("%d = 1 ", a);
            for(c = 2; c < a; c++)
            {
               if(a%c == 0)
               printf("+ %d ", c);
            }
            printf("
");
         }
   }
   return 0;
}
int isperfect( int x)
{
   int i, sum =0;

   for( i=1; i<x ; i++)
   {
      if( x%i == 0 )
      sum += i;
   }
   if ( sum == x )
     return 1;
   else
     return 0;
}


And FINALLY got…



6 = 1 + 2 + 3
28 = 1 + 2 + 4 + 7 + 14
496 = 1 + 2 + 4 + 8 + 16 + 31 + 62 + 124 + 248
8128 = 1 + 2 + 4 + 8 + 16 + 32 + 64 + 127 + 254 + 508 + 1016 + 2032 + 4064


And with that, I can now go to bed early, thanks for your help Wily and also sorry for my scrubbiness. :lol:

Cool : ) looks pretty good. I’d say you can get away with only going 1/2 way when looping for factors, since you can’t have a factor more than half of a number, but I think it’s in a decent state to turn in at least.

Still a badly written problem, since the solution is a clusterfuck of unoptimized at this level of programming knowledge. But it’s still a decent problem for working through since it makes you think

Hahaha, if there’s a way you can make it better then I’m all ears… err eyes. I’m trying to improve at this. :slight_smile:

No, not without some more complicated things (like arrays, pointers, cache, etc). For your simple assignment it’s fine. Assuming you stick with programming, look at this in 5 years and you’ll see a much different solution

Here’s my new homework assignment right now. Again any help is appreciated, especially since I have to study for 3 midterms this week and I’m worried I won’t have any time to work on this. Welcome to college life I suppose lol. :sad:

Of course it goes without saying that I’m going to be putting in a decent amount of work in this as well. Can’t expect the pros here to do all the work for me. Thanks in advance. :slight_smile:

[details=Spoiler]Due Friday 11/4

Question
Suppose that you have a party and invite 30 people. What do you think is the probability that two of these people have the same birthday?

Answering this Question using Simulation
For this lab, you are to write a program that uses simulation to answer this question. The program should simulate a party by selecting birthdays randomly, and then checking to see if two of the birthdays are the same. The probability that two people have the same birthday can be determined by simulating a large number of such parties, and keeping track of how many times there are two people with the same birthday.
Make your program flexible by allowing the user to specify the number of trials to run (i.e., the number of parties to simulate) as well as the number of people to invite. Use the time function to seed the random number generator.

Hints
· Write a function with prototype int party(int n) that will simulate one party with n guests. The function will return 1 if any two of the guests have the same birthday (i.e., born on the same day of the year, not necessarily in the same year) and returns 0 otherwise. To be more precise, the function party should return 1 if any two birthdays are the same, regardless of whether any other guests have the same birthday. For example, if two pairs of guests have the same birthday, the function returns 1. If three guests have the same birthday, the function returns 1. And so forth. The only time the function returns 0 is if all the birthdays are different.
· In the function party, use the function rand to generate the random birthdays. (A birthday may simply be a number between 1 and 365. You can ignore leap years).
· Call srand once at the beginning of main. (Do not call srand in the function party. If you do, and pass it the same seed every time, your function will simulate the same party every time it is called.)
· In the function party, use an int array to record birthdays that have been assigned. Give some thought to how large the array should be, and how you will record birthdays. There is more than one reasonable way to do this.
· Aside: If you understand probability theory, you might be able to answer this question analytically. For many other questions of this sort, however, simulation is the only practical way to find an answer.

Report
Submit a report at the beginning of your lab session. Your report should include a printout of your source code and the dialog for three sample runs, as follows:
o Invite 30 people and simulate 10,000 parties
o Invite 30 people and simulate 1,000,000 parties
o Invite 40 people and simulate 100,000 parties
Print the probability of two guests having the same birthday as a percentage, with two digits to the right of the decimal point. The dialog for the first sample run should look like the following (the percentage given is not correct):
Enter the number of guests: 30
Enter the number of parties: 10000
The probability that two guests have the same birthday is 12.34%[/details]

Won’t work if you try to compile, but the logic is the key. This assume you’ve learned arrays, I’m not sure if it’s possible to do this without them. The assignment mentions them so yeah, make sure you learn them well.




//returns 1 if any people share a birthday
int party(int numPeople)
{
  //generate birthdays
  int birthday[numPeople]; //this might not work actually in C++, not sure if you can declare array sizes dynamically
  for(int i = 0; i < numPeople; i++)
  {
    birthday* = rand() % 365; //ignore leap year, gives us a number between 0 and 355 to represent the birthday
  }

  for(int i = 0; i < numPeople; i++)
  {
  //double loop, this checks each person against each other person in the most straightforward way possible
    for(int j = i + 1; j < numPeople; j++)
    {
        if(birthday* == birthday[j]) //true if they share a birthday
          return 1; //we can return 1, 2 people shared a birthday
    }
  }

  return 0; //this only ever gets here if there were no matches
}

int main()
{

int numPeople, numTrials;
int success = 0;
srand(time()); //this seeds the random number generator based on the current millisecond
cout << "How many trials to run? ";
cin >> numTrials;
cout << endl << "How many people per party? ";
cin >> numPeople;

for(int currentTrial = 0; currentTrial < numTrials; currentTrial++)
{
  int nPartyResult = party(numPeople);
  if(nPartyResult == 1)
    success++;
  }

  float successPercentage = (float)success / (float)numTrials * 100;
  //output the result
  cout << "The probability that two guests have the same birthday is " << dSuccessPercent << endl;
  return 0;
}



I actually don’t think you can code the array size dynamically like I did. I remember it being a big issue when we would do assignments like this, and the teacher would just have us do it as a big number. Technically it’s a bug since you can crash the program, but practically it works. Since the most you need to simulate is 40 people for the assignment, I’d just declare the array as size 100 to give yourself some breathing room. Even something like 365 is a quirky answer to this solution because the chances of having people share birthdays is automatically 100% once you go over 365 people, so there’s no reason to run the program if that many people are going ; )

Found time to look over your code, read and messed with it for a bit


include <stdio.h>
#include <stdlib.h>
int party(int n)
{
   int numPeople, numTrials, nPartyResult, dSucess, birthday, i, j;
   int success = 0, currentTrial = 0;
   int successPercentage;
   srand(time());

   printf("Enter the number of guests: 
");
   scanf("%d", &numPeople);
   printf("Enter the number of parties: 
");
   scanf("%d", &numTrials);

   for(currentTrial = 0; currentTrial < numTrials; currentTrial++)
   {
  int nPartyResult = party(numPeople);
  if(nPartyResult == 1)
    success++;
   }
{
  float successPercentage = (float)success / (float)numTrials * 100;
  printf("The % that two guests have the same birthday is %d
", dSucess);
   return 0;
}
party(numPeople);
{
  for(i = 0; i < numPeople; i++)
  {
    birthday* = rand() % 365; //ignore leap year, gives us a number between 0 and 355 to represent the birthday

  for(i = 0; i < numPeople; i++)
  {
    for(j = i + 1; j < numPeople; j++);
  }
        if(birthday* == birthday[j]) //true if they share a birthday
          return 1; //we can return 1, 2 people shared a birthday
    }
  }
  return 0; //this only ever gets here if there were no matches
}

And the only errors I got were


"Project4ver2.c", line 26: warning: statement not reached
"Project4ver2.c", line 30: cannot dereference non-pointer type
"Project4ver2.c", line 36: cannot dereference non-pointer type
"Project4ver2.c", line 36: cannot dereference non-pointer type

And welp, it looks like I didn’t use arrays at all. :shake:

Your brackets are all completely messed up, and you don’t have a main. Your main is the function that’s called when you run the program, without one it won’t work. You really need to look at each line and understand what you’re trying to accomplish. Go back and put comments in. You completely butchered what I wrote with a ton of alterations that show you don’t really understand what you’re doing. Is this your major?

I don’t think you understand functions, it looks like you don’t understand loops, and you didn’t even attempt to use arrays.

Go back, and comment each line of code with what you think it is doing. Then you’ll see the logic flow, and understand what you’re doing wrong.

Yes what he said, pretend to explain it out loud to someone, even though no one is there. I used to do this in my mind when I wasn’t clear on what I just did or intended to do.

Or I write it down in english (and sometimes math) what I mean to do. If I can explain it that way, I can break it down into smaller, logical pieces.

As far as dynamic allocation, C and C++ offer ways:



// The following includes are required
#include <cstdlib> // For malloc, the C way of creating arrays.
#include <vector> // Include this to use the c++ STL vector.
#include <iostream> // Need for cout and cin.
using namespace std; //This allows you to shorten the code, instead of writing std::vector<int> you don't need the std:: on every line you use something like vector

int main() { // main required by all c++ programs
    //generate birthdays
    int numPeople = 365; // For no reason, I used 365 as a nice round number

    // Using C's way to create an array.
    // I create an integer Pointer. int *birthday =
    // I then call malloc and tell it how many int's to create. malloc ( sizeof(int) * numPeople)
    // I then make sure it knows malloc should return an integer Point array = (int *) malloc
    int *birthday = (int*) malloc( sizeof(int) * numPeople);

    // Using the c++ way with STL, I can create a vector, which is equivalent to an array.
    // vector<int> let's c++ know I want an array of integers.
    // Then I want to let it know how many integers to create in my array: = vector<int>(numPeople);
    vector<int> birthdayVector = vector<int>(numPeople);

    birthday[0] = 1; // The first index of a C array is 0.
    birthday[numPeople - 1] = numPeople; // The last index of a C array is its length minus 1.

    cout << numPeople << endl;
    cout << birthday[0] << " -> " << birthday[numPeople - 1] << endl; // Print out the first and last element in the C array.

    birthdayVector.front() = 1; //Special accessor, equivalent to birthdayVector[0] = 1;
    birthdayVector.back() = numPeople; //Special accessor, equialent to brithdayVector[numPeople - 1] = numPeople;
    cout << birthdayVector.front() << " -> " << birthdayVector.back() << endl;

    // Just showing you how to access individual elements.
    birthday[22] = 2;
    cout << "This many people have a birthday at the 22nd day of the year (array ): " << birthday[22] << endl;

    birthdayVector[22] = 2;
    cout << "This many people have a birthday at the 22nd day of the year (vector): " << birthday[22] << endl;

    // Now you can figure out how to use a for loop on either the vector or the C array.
    // You'll need to find the total length and you'll need to start at zero.

    return 0; //Zero means no error, any number above zero is a program specific error code.
}


Vectors are definitely the easiest way to do this, but since he just learned Arrays, I doubt he should be messing with Malloc or Vectors for this assignment. I mean that basically tells his professor “Somebody else wrote this!”

But the malloc thing is definitely the way to declare the array dynamically at runtime, not the way I wrote earlier, haha

Sup. Didn’t know we made another one of these.

malloc() don’t cost anything. It’s free().

Holy god that sucked. I’ll go back to getting pissed at Javascript now.

Are we doing bad programming jokes, because I only have 1 (besides the 10 types of people joke everyone knows)

The best part of UDP Jokes? I don’t care if you get them or not

Subscribing.

Learning Java this semester, planning on majoring in Computer Science. Still at a low level unfortunately. Over halfway through the semester and we’re just now learning to use multiple methods in a program. Our biggest project so far has been programing the game Mastermind (game makes a random number and gives user however many guesses and some hints, number of correct digits and sum of said digits.) Hasn’t been graded yet, but I’m sure my code could have been wayy more efficient.