B2092 Switch Light 【Getting Started】

Original title link: switch light

switch light

topic description

Suppose there is NNN lamps (NNN is not greater than5000 5000positive integer of 5000 ), from1 to 11 toNNN is numbered sequentially, and all are in the open state at the beginning; the first person (1 1No. 1 ) turns the lights all off, and No. 2 (2 2number 2 ) will be numbered2 2lights in multiples of 2 are turned on, and the third person ( 3 3number 3 ) will be numbered3 3Multiples of 3 do the opposite (ie turn on lights off and turn off lights on). According to the ascending order of the numbers, the following people are all the same as3 3The same as No. 3 , do the opposite for all lights with multiples of their own numbers. Ask when theNNthAfter the operation by N people, which lights are turned off?

input format

The input is one line, an integer NNN , is the number of lamps.

output format

The output is one line, outputting the numbers of the lights that are turned off in order. There is a space between numbers.

Example #1

Sample Input #1

10

Sample output #1

1 4 9

Example #2

Sample Input #2

5

Sample output #2

1 4

Idea:
At the beginning, all the lights are on. If they are turned off at the end, then this light should be turned on and off an odd number of times in the whole process, so the factor that satisfies the light that is turned off at the end should be an odd number, and Because the factors of a perfect square number are odd numbers (this is a theorem, it has been determined), then we only need to find which numbers from 1 to n are perfect square numbers, then these lights are turned off in the end.

Why is the number of factors of a perfect square number odd

Because for a number x, there is a factor m, there must be another factor x/m, two pairs, and the factor corresponding to the square root of a perfect square number is itself, so there are a total of odd factors.

import java.util.Arrays;
import java.util.Scanner;
import java.util.*;

public class Main {
    
    
    public static void main(String[] args) {
    
    
        Scanner in=new Scanner(System.in);
        int n=in.nextInt();
        for(int i=1;i<=n;++i){
    
    
            if(i*i<=n)
                System.out.print(i*i+" ");
        }
    }
}


Guess you like

Origin blog.csdn.net/xiatutut/article/details/129642334