有n盞燈,編號爲1~n。第1我的把全部燈打開,第2我的按下全部編號爲2的倍數開關(這些燈將被關掉),第3我的按下全部編號爲3的倍數的開關,以此類推。一共有k我的,問最後有哪些燈開着?輸入n和k,輸出開着的燈的編號。k<=n<=100spa
樣例輸入 7 3code
樣例輸出 1 5 6 7blog
#include<stdio.h>
#include <stdlib.h> typedef struct light{ int state; // state 爲 0 時表明燈是關着的,爲 1 時表明燈是亮着的 struct light *next; }; int main(void) { int num, k, i, j; light *light_state = NULL; light *head = NULL, *temp = NULL; printf("請輸入燈的數量n,人的數量k:"); scanf("%d %d", &num, &k); for(i = 0; i < num; i++) // 建立長度爲 num 的鏈表 { light_state = (light*)malloc(sizeof(light)); if (head == NULL) head = light_state; else temp->next = light_state; light_state->next = NULL; light_state->state = 0; temp = light_state; } for(j = 0; j < k; j++) { light_state = head; for(i = 0; i < num; i++) { if((i + 1) % (j + 1) == 0) // 燈的編號符合須要對應的人按開關時 if(light_state->state == 0) { light_state->state = 1; } else if(light_state->state == 1) { light_state->state = 0; } light_state = light_state->next; } } printf("開着的燈的編號爲:"); light_state = head; for(i = 0; i < num; i++) { if(light_state->state == 1) { printf("%d ", i+1); } light_state = light_state->next; } printf("\n"); system("pause"); }