I am taking C programming class. I was wondering if you can help me with this qu
ID: 3914379 • Letter: I
Question
I am taking C programming class. I was wondering if you can help me with this question of my assignment. In an effort to try to understand energy consumption in their dorm some students decide to simulate how often lights are used. Let us say there are n students conducting the experiment using their n dorm rooms (numbered 1 through n). The system they devised for testing is as follows. First the light in each room is turned off. At some point during the day each of the students will walk down the hallway. The student who lives in room i will first flip the switch in their room and then travel i more rooms to flip another switch, repeating this process until they reach the end of the hallway. Your job is to figure out how many lights will be on at the end of the day. For example, if there are 20 students, the student who lives in room 5 will flip the switches in rooms 5, 10, 15, and 20. Here is an explanation of the second sample test case when there are 5 students. The switch in room 1 is only flipped by the person who lives there so it is on. The switches in rooms 2 3 and 5 are flipped by the person who lives in each and the person from room 1, so they are all off. The switch in room 4 is flipped by the people from rooms 1, 2, and 4, so it is on at the end of the day. Rooms 1 and 4 have their lights on at the end of the day, so the proper output is 2.
Explanation / Answer
#include<stdio.h>
int main()
{
int n,i,j,x; //n represents no of rooms,students
scanf("%d",&n);
int a[n];
for(i=1;i<=n;i++) //we initialise all values from a[1] to a[n] to 0.This implies initially each a[i]=0; room is not visited by any student
for(i=1;i<=n;i++)
{
a[i]++; //This for loop will count by how many students each room is visited by
j=i;
while(j<=n)
{
j=j+i;
if(j<=n)
a[j]++;
}
}
for(i=1;i<=n;i++)
{ //This for loop checks which rooms will be in on state by end and give
if(a[i]%2==1) count of it
x++;
}
printf("%d",x);
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.