C language switch light experiment

Experiment Description
There are n lamps, numbered 1~n. The first person turns on all the lights, the second person presses all the switches numbered as multiples of 2, the third person presses all the switches numbered as multiples of 3, and so on. When the switch is pressed, the lights that are turned off will be turned on, and the lights that are on will be turned off. There are k people in total, output the number of the last light that was turned on. n and k are entered at runtime, 1≤k≤n≤1000. When outputting, each line outputs 10 serial numbers and uses the output format to achieve left alignment.
Code

  • Use 0 to indicate that the light is off and 1 to indicate that the light is on. First define an array and assign all values ​​to 0.
  • Use the remainder method to determine whether the m-th person wants to operate the n-th lamp.
  • After pressing the switch, 0 becomes 1, and 1 becomes 0. Finally, all elements that are 1 are output.
/*n人开关灯实验*/
#include <stdio.h>
#include <stdlib.h>

int main()
{
    
    
    int arr[1000],lnum,pnum,count=0;

    printf("输入灯的数目:");
    scanf("%d",&lnum);
    for(int i=0;i<lnum;i++)   //赋初值
        arr[i]=0;
    printf("输入人的个数:");
    scanf("%d",&pnum);
    
    for(int m=1;m<=pnum;m++) //依次开关灯;
    {
    
    
        for(int n=1;n<=lnum;n++)
        {
    
    
            if(n%m==0)
            {
    
    
                if(arr[n-1]) arr[n-1]=0;
                else arr[n-1]=1;
            }
        }
    }

    for(int i=0;i<lnum;i++)  //输出开着的灯的编号
    {
    
    
        if (arr[i]!=0)
        {
    
    
            printf("%-4d",i+1);
            count++;
            if (count%10==0) printf("\n");
        }
    }

    return 0;
}

Number of experimental results
Input lights: 200
Enter the number of people: 101
1 4 9 11 13 14 15 17 18 19 20 21 29 31 37 37 43 44 47
53
56 59 60 67
68 70 71 72 73 75 76 79 81
83 89 90 92 97 98 99 100 101 103 107 109 112 113 116 117 121
124 127 131 132 137 139 143 144 147 148 14 9 151 153 154 156
157 162 163 164 165 167 168 169
171
172 173 175 179 181 182 187 188
191 193 195 197 198 199

Guess you like

Origin blog.csdn.net/weixin_42145554/article/details/128159118