C/C++ Programming Learning-Week 4 ⑤ Switch lights

Topic link

Title description

Suppose there are N lights (N is a positive integer not greater than 5000), numbered in sequence from 1 to N, and all are turned on at the beginning; there are M individuals (M is a positive integer not greater than N) and also from 1 to M Number sequentially.

The first person (No. 1) turns off all the lights, the second person (No. 2) turns on the lights that are multiples of 2 and the third person (No. 3) reverses the lights that are multiples of 3 (ie , Turn off the light that is turned on, and turn on the light that is off). According to the increasing order of the number, all the people in the future will be the same as No. 3, and all the lights that are multiples of their own number will be processed in reverse.

Excuse me: After the M-th person operates, which lights are turned off, output their numbers from small to large, separated by commas.

Input format
Input positive integers N and M, separated by a single space, M ≤ N.

Output format
Output the numbers of the lights turned off in sequence, separated by commas.

Sample Input

10 10

Sample Output

1,4,9

Ideas

To simulate the process of switching lights, you can define a tag array to indicate the status of the lights.

C language code:

#include <stdio.h>
int a[5001] = {
    
    0};//0为关闭,1为打开。将数组全初始为0,因为第一个人会对所有灯操作,所以相当于从第二个人开始,初始时灯是关的
int main()
{
    
    
    int n, m, i, j, t = 0;
    scanf("%d%d", &n, &m);
    for (i = 2; i <= m; i++)	//模拟人从2号到m号
        for (j = i; j <= n; j = j + i)	//用j + i表示倍数
            a[j] = (a[j] == 1 ? 0 : 1);	//等价于:if(a[j] == 1)
    for (i = 1; i <= n; i++)
        if (a[i] == 0)//选出关闭的输出
        {
    
    
            if (t == 0)
            {
    
    
                printf("%d", i);
                t = 1; 
            }
            else printf(",%d", i);
        }
    return 0;
}

C++ code:

#include<bits/stdc++.h>
using namespace std;
int vis[5005];
int main()
{
    
    
	int n, m;
	while(cin >> n >> m)
	{
    
    
		memset(vis, 0, sizeof(vis));
		for(int i = 1; i <= m; i++)		//人 
		{
    
    
			for(int j = i; j <= n; j++)	//灯 
			{
    
    
				if(j % i == 0)
				{
    
    
					if(vis[j]) vis[j] = 0;
					else vis[j] = 1;
				}
			}
		}
		int f = 0;
		for(int i = 1; i <= n; i++)
			if(vis[i])
			{
    
    
				if(f == 0)
				{
    
    
					cout << i;
					f = 1;
				}
				else cout << "," << i;
			}
		cout << endl;
	}
	return 0;
}

Guess you like

Origin blog.csdn.net/qq_44826711/article/details/112908301