Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

I need help answering a homework problem [Fortran]

0 votes
asked Nov 17, 2019 by Dat fortran
The full question is:

Suppose that row of closed rooms are numbered 1,2,3,…. up to a user specified number of room (N). Beginning with room 2, we open the doors of all the even-numbered rooms. Next, beginning with room 3, we go to every third room, if the room number is even then we open its door if its closed and close it if it is open. We repeat this procedure with every fourth room, then every fifth room (if the room number is even), and so on. Write a program to determine which rooms will be closed when this procedure is completed.

for N=50 the answer should be: 1,3,4,5,7,9,11,13,15,16,17,19,21,23,25,27,29,31,33,35,36,37,39,41,43,45,47,49

I have it working a bit, but missing 16, and 36

my code for it is;

PROGRAM P1
IMPLICIT NONE
INTEGER, ALLOCATABLE :: Y(:)
LOGICAL, ALLOCATABLE :: X(:)
INTEGER ::N,I,Z
    PRINT *, "PLEASE ENTER N"
    READ*,N
    Z=0
ALLOCATE(Y(N),X(N))

DO I=1,N
Y(I)=I
IF (0==MOD(I,2)) THEN
X(I)=.TRUE.
ELSE
X(I)=.FALSE.
END IF
IF (I==2) THEN
X(I)=.FALSE.
END IF
END DO

DO I=1,N
    DO Z=0,N,I
        IF (Z==0 .OR. Z==4 .OR. I==2) CYCLE
        IF (I==2) EXIT
        IF (0==MOD(I,Z)) THEN
        X(I)=.NOT.X(I)
        END IF
    END DO
END DO

DO I=1,N
    IF(X(I) .EQV. .TRUE.) THEN
        PRINT *, Y(I)
    END IF
END DO
DEALLOCATE(Y,X)
END PROGRAM P1

1 Answer

0 votes
answered Dec 24, 2023 by minglho (140 points)

If I understand your problem statement correctly, as you go through the doors by multiplies of I, you would change the state of the door if the door number is even. For example, as you go through multiples of 3, only doors 6, 12, 18, etc. would change its state from open to close or vice versa.

Where in your code do you test that a door is even before you change its state?

Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...