Jump to content

can someone help???

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
2 replies to this topic

#1
dnagirl

dnagirl

    Newbie

  • Members
  • Pip
  • 1 posts
I have C++ homework that's due tonight and for some reason I'm dumbfounded and can't figure out how to do the output. The problem is this:

Suppose that a row of closed mailboxes are numbered 1 through 150 and that beginning with mailbox 2, we open the doors of all the even-numbered mailboxes. Next, beginning with mailbox 3, we go to every third mailbox, opening its door if it is closed and closing it if it is open. We repeat this procedure with every fourth mailbox, then every fifth mailbox, and so on. Write a program to determine which mailboxes will be closed when this procedure is completed.

i have the whole program done but when i create the loop for the output it lists all of the mailboxes. i need to define the closed mailboxes but im not sure how. here is my program and what ive come up with so far.
#include "stdafx.h"
#include <iostream>

using namespace std;


int _tmain(int argc, _TCHAR* argv[])
{\
// ignore 0 mailbox
bool mailbox[151];
for (int i=1; i<=150; i++)
mailbox[i] = false; // closed
for (int j = 2; j <= 151; j+=2) {
for (int i = j; i <= 151; i += j){
if (mailbox[i] == false)
mailbox[i] = true; // open mailbox
else
mailbox[i] = false; // mailbox closed
}
}
for (int i=1; i<=150; i++){

if (mailbox[i] == false) // if closed output mailbox number
cout << i << endl;
}

return 0;
}


#2
WingedPanther

WingedPanther

    A spammer's worst nightmare

  • Moderators
  • 16,831 posts
At first glance it looks like your code should work. What is happening that you didn't expect?
Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

#3
G_Morgan

G_Morgan

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 537 posts
Sounds like a sieve of eratosthenes (sort of) in reverse. I'd modify it so that it says 'for (int i = j * j; i <= 151; i += j){'

I think the problem is you are including the one you are supposed to keep. When it says start at 3 I assume it means keep that one and blank the rest. Otherwise it would close them all.

If you don't like the above trick then change it to 'for (int i = j + 1; i <= 151; i += j){'.

In both cases you should find it closes all but the prime numbers.