이 페이지는 코딩도장 데이터의 읽기 전용 정적 보관본입니다.

Light More Light

출처: programming challenges

우리 학교에는 복도 불을 켜고 끄는 마부(Mabu)라는 사람이 있다. 전구마다 불을 켜고 끄는 스위치가 있다. 불이 꺼져 있을 때 스위치를 누르면 불이 켜지고 다시 스위치를 누르면 불이 꺼진다. 처음에는 모든 전구가 꺼져 있다. 마부라는 사람은 특이한 행동을 한다. 복도에 n개의 전구가 있으면, 복도를 n번 왕복한다. i번째 갈 때 그는 i로 나누어 떨어지는 위치에 있는 스위치만 누른다. 처음 위치로 돌아올 때는 아무 스위치도 건드리지 않는다. i번째 왕복은 (이런 이상한 행동을 하면서) 복도를 한 번 갔다가 오는 것으로 정의된다. 마지막 전구의 최종 상태를 알아내자. 과연 그 전구는 켜져 있을까 아니면 꺼져 있을까?

Input

복도에 있는 n번째 전구를 나타내는 숫자가 입력된다. (2^32-1 이하의 정수가 입력된다.) 0은 입력의 끝을 의미하며 그 값은 처리하지 않는다.

Output

그 전구가 켜져 있으면 "yes"를, 꺼져 있으면 "no"를 출력한다. 테스트 케이스마다 한 줄에 하나씩 출력한다.

Sample Input

3
6241
8191
0

Sample Output

no
yes
no

2014/03/12 23:20

pahkey

Input에서 복도에 있는 n번째 전구를 -> 복도에 있는 전구의 개수 n을 로 하는게 좀 더 정확한 표현 아닐까요? - 조현우, 2020/11/04 09:49
'마지막 전구의 최종 상태를 알아내자.'에서 '마지막 전구'의 정의가 무엇인가요? 처음 위치로 부터 가장 먼 곳의 전구? 아니면 마부가 마지막으로 스위치를 누른 전구? 'Sample Input'의 '3'경우 최종 상태는 3번, 2번 전구는 off, 1번 전구는 on 인데(처음 위치를 기준으로 부터 전구 번호 1, ...)... 마지막 전구의 정의가 처음 위치로 부터 가장 먼 것은 3번 전구, 마지막 스위치를 누른 전구는 2번 전구입니다. - Charles, 2022/05/05 14:57

103개의 풀이가 있습니다.

Java입니다. 수학문제네요.

마지막 전구가 n번째 전구일 때, n의 약수인 i번째 왕복마다 마지막 전구를 누릅니다.
즉, (마지막 전구는 처음에 꺼져 있으므로)
n의 약수의 갯수가 홀수이면 → 최종 상태는 켜져있게 되고,
n의 약수의 갯수가 짝수이면 → 최종 상태는 꺼져있게 됩니다.

1) 그럼 1~n 수 중 n의 약수가 나올 때마다 스위치를 누르게 해서 최종 결과를 보면될까요?
boolean light=false; for(i=1;i<=n;i++) if(n%i==0) light=!light;
System.out.println( (light)?"yes":"No" );
그런데 이런식으로 짜면 (문제에서 지정한) 2^32-1=4294967295 같은 큰 수를 입력했을 경우 연산이 굉장히 느립니다.
(2^31-1=2147483647만 입력해도 프로그램이 작동을 멈춥니다)
    ⇒ 그래서 다른방법을 찾아야 합니다.

2) 어떤 수가 홀수개의 약수를 가지고, 어떤 수가 짝수개의 약수를 가질까요?
1의 약수={1} → 홀수개(on), 2,3,5,7,11 등 1과 자신만을 약수로 가지는 수(소수) → 짝수개(off)
12의 약수={1,2,3,4,6,12} → 짝수개(off), 15의 약수={1,3,5,15} → 짝수개(off)
16의 약수={1,2,4,8,16} → 홀수개(on), 25의 약수={1,5,25} → 홀수개(on)
즉, 1 4 9 16 25 36 49 ... 등 어떤 수의 제곱수(m^2)만이 홀수개의 약수를 가집니다 → (on)
 ⇒ 입력된 값 n이 어떤 수의 제곱인지(i*i) 확인하면 됩니다. 
package h_light_more_light;
import java.util.Scanner;
public class LightMoreLight {
    public static void main(String[] args) {
        Scanner in=new Scanner(System.in);
        boolean light; long i; int j, M, N=150; // N:입력값 갯수의 한계
        long[] n=new long[N];
        for(j=0;j<N;j++){ /*입력*/
            n[j]=in.nextLong(); 
            if(n[j]==0) break; 
        } //(2^32-1=4294967295 이하의 정수가 입력된다.)
        M=j; //M:입력받은 값의 수

        for(j=0;j<M;j++){ /*연산*/ //입력값을 하나씩 처리
            light=false;
            for(i=1; i*i<=n[j]; i++) if(i*i==n[j]) light=true;
            System.out.println( (light)?"yes":"No" );
        }
}}
#입출력예시
3
6241
8191
1
4294967295
12
11
15
16
2147483647
3600
3969
6400
0
No
yes
No
yes
No
No
No
No
yes
No
yes
yes
yes

2014/03/13 01:52

Katherine

int값은 2^32-1개의 데이터를 가지고, int의 양수는 0~2^31-1까지이고 그 이상은 음수인데, 여기서 입력값이 2^32-1이하의 정수는 int의 양수값보다 크므로, 입력값은 int가 아닌 long형을 사용했습니다. 메모리낭비인가요? int형으로 2^32-1이하의 정수를 다 표현할 다른 방법이 있을까요? - Katherine, 2014/03/13 01:57
for(i=1; i<=n[j]; i++) if(i*i==n[j]){ light=true; break; } 이런식으로 처리했더니 2147483647같은 큰 수를 입력하니까 작동을 멈추네요.. 왜그럴까요? - Katherine, 2014/03/13 01:59
왜긴요. i*i가 2^31보다 커졌는데 32비트 자료형이라 음수가 되어버려서 무한루프에 빠지는 거죠 - Kim Jaeju, 2014/03/13 15:10
멋진 해법 잘 봤습니다. ^^ - pahkey, 2014/03/14 14:12
@길가의풀 님 감사해요 ㅋㅋ @Kim Jaeju 님, for(i=1; i*i<=n[j]; i++) if(i*i==n[j]) light=true; 이거나, for(i=1; i<=n[j]; i++) if(i*i==n[j]){ light=true; break; } 요거나 for(i=1부터시작 1씩증가) if(i*i==n[j])가 되면 → light=true; 시키고 이 i에서 for루프중단. 똑같은 수행아닌가요?? - Katherine, 2014/03/14 18:22
i=4000000으로 하고 i*i 값 찍어보세요. 무슨 말인지 이해가실테니 그리고 두 코드는 로직상으로도 전혀 다르죠 - Kim Jaeju, 2014/03/14 18:50
@Kim Jaeju님 두 코드 모두 i*i<=n[j]일 때 루프중단시키는 거 아닌가요? 두번째 코드도 if(i*i==n[j]) → break;인데... 네 공부 더 해볼게요 ㅠㅠㅋㅋ - Katherine, 2014/03/15 08:01
for문에서 I의 범위가 다르잖아요 그리고 안 나오는 이유는 정수형 범위 초과라니까요? 왜 알려드려도 다른 말씀을 하시는지 - Kim Jaeju, 2014/03/17 09:31
네네 Kim Jaeju님 알겠습니다^^ - Katherine, 2014/03/17 14:14
역시 수학을 잘해야 한다는 결론이...감사합니다. - 예강효빠, 2017/06/03 03:45

파이썬 2.7.6입니다.

새로운 건 없고 윗분들의 알고리즘과 코드를 참고하여 나름대로 만들어 보았습니다.

잘못된 내용이 있다면 말씀해 주시면 감사하겠습니다.

import math

def light_switch(input_num):
    return "yes" if math.sqrt(input_num) % 1 == 0 else "no"


print map(light_switch, [3, 6241, 8191])

2014/03/17 10:56

deukey

소숫점이 있는지 없는지 체크하는 부분이 멋지네요 ^^ - pahkey, 2014/03/17 11:07
엄청 깔끔합니다. ㅎㅎ - 뤼크, 2020/03/29 01:21

파이썬입니다.

import unittest
import math

def mabu(n):
    lights = [False] * n
    for i in range(1, n+1):
        for j in range(1, n+1):
            if j%i==0: lights[j-1] = not lights[j-1]
    return lights[-1] and "yes" or "no"

def mabu2(n):
    return str(math.sqrt(n)).split(".")[-1] == "0" and "yes" or "no"

class MyTest(unittest.TestCase):
    def testMabu(self):
        for n in [3, 6241,8191]:
            print mabu(n)

    def testMabu2(self):
        for n in [3, 6241,8191, 2**32-1]:
            print mabu2(n)

if __name__ == "__main__":
    unittest.main()

mabu2 는 Katherine님의 알고리즘을 조금 변형해 본것입니다.

2014/03/14 14:29

pahkey

python3

while 1:
    n = int(input().strip())
    if n == 0:
        break
    print('yes' if n**0.5 % 1 == 0 else 'no')

2016/03/22 16:28

디디

def f(num1):
    status = False
    for i1 in range(1, num1+1):
        if num1%i1 == 0:
            status = not status
    print((lambda x:'yes' if x else 'no')(status))

f(3)
f(6241)
f(8191)

2017/09/01 09:29

piko

파이썬 3.4 입니다. 수학문제를 푼건 아니고 ^^, 1 번부터 n 번째까지 왕복할때마다 마지막 전구 스위치를 누르게 되면 그때 마다 1씩 더해서 마지막에 누른 총 횟수가 짝수인지 홀수인지에 따라 판단하도록 했습니다.

def last_light(total):
    action = 0
    for i in range(total):
        if total%(i+1) == 0:
            action += 1
        else:
            pass    
    return 'yes' if action % 2 == 1 else 'no'

total_list = []
while True:
    total = int(input())
    if int(total) == 0:
        break
    total_list.append(total)

output = list(map(last_light,total_list))
for i in output:
    print(i)

2014/09/24 19:48

돌구늬ㅋ~썬

n 번째 전구는 i 가 n의 약수일때 on/off 됩니다. 약수의 개수가 홀수이면 켜지고 짝수이면 꺼지죠.

약수의 개수가 홀수인 경우는 완전제곱수밖에 없습니다.

def onOff(num):
    if num < 1:
        return False
    return num**0.5 == int(num**0.5)


def main():
    results = []
    while True:
        a = int(raw_input(""))
        if a != 0:
            results.append(onOff(a))
        else:
            break
    for onoff in results:
        print "yes" if onoff else "no"

main()

2014/12/11 18:15

룰루랄라

Ruby, 무식하게 다 켜고 꺼서 판단한 버전. ㅋ

def last_bulb_on?(bulb_count)
  bulbs = [false] * bulb_count
  (1..bulb_count).each do |v|
    bulbs.map!.with_index { |b, i| ( (i + 1) % v == 0 ) ? !b : b }
  end

  puts "#{bulb_count}: #{bulbs.last ? "yes" : "no"}"
end

[3, 6241, 8191].each { |v| last_bulb_on? v }

2014/12/31 01:22

놀란눈

Perl 캐서린님이 잘 풀이 해 놓으셨네요. 약수의 갯수는 각 소인수 승수 + 1의 곱과 같으니 제곱수만 체크하면 되죠.

while(<>){
    exit 0 if $_==0;
    $_==int(sqrt($_))**2?print"yes":print"no";
    print"\n"
}

2015/01/07 18:50

*IDLE*

python 입니다.

def func(n, r=False):
  for i in range(1, n+1):
    if n%i == 0: r = not r  

  return r

print func(3)
print func(6241)
print func(8191)

2015/01/08 19:02

Sang Brian

C#으로 작성했습니다. 캐서린님께서 너무 쉽게 풀이해주셨네요. 안그랬으면 말씀해주신 1번 풀이법으로 고생하고 있었을 것 같아요. 감사합니다.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CodingDojang
{

    class CodingDojang
    {
        void Main(string[] args)
        {
            LightMoreLight.Answer();
        }
    }

    public class LightMoreLight
    {

        public void Answer()
        {

            var inputLine = Console.ReadLine().ToString();
            List<string> inputs = new List<string>();

            while(inputLine != "0")
            {
                inputs.Add(inputLine);
                inputLine = Console.ReadLine().ToString();
            }

            foreach (var input in inputs)
            {

                var sqrt = Math.Sqrt(long.Parse(input));
                string value = string.Empty;
                sqrt % 1 == 0 ? value = "yes" : value = "no";
                Console.WriteLine(value);
            }

        }

        public bool LightMoreLight(int n)
        {
            return Math.Sqrt(n)%1 == 0;
        }

    }

}

2015/01/27 20:43

Straß Böhm Jäger

Using python

xor로 짯는데 아무래도 저렇게 하면 big number에서 메모리가 터지는군요... 생각보다 python sqrt연산이 빨라서 놀랐습니다..허허

import math

def LightMore1(light):
    switch = 0
    for i in range(1,light+1):
        if light % i == 0:
            switch ^= 1
    if switch == 1:
        print "ON"
    else:
        print "OFF"

def LightMore2(light):
    if math.sqrt(light)%1 == 0:
        print "ON"
    else:
        print "OFF"

LightMore1(2)
LightMore1(6241)
LightMore2(6241)


2015/03/31 17:12

freeefly

    Sub Main()
        Dim input As Long = Val(Console.ReadLine)

        Console.WriteLine(IIf((Math.Sqrt(input) Mod 1 = 0), "yes", "no"))
    End Sub

2015/06/17 23:27

Steal

int root(double input)
{
    double n = 2;

    while (n*n < input)
    {
        n += 1;
    }

    if (n*n == input)
        return 1;
    else
        return 0;
}

void exce42()
{
    double *arr, input;
    int len = 0, end = -1;

    arr = (double *)malloc(sizeof(double));

    while (1)
    {
        scanf_s("%lf", &input);
        if (input == 0)
            break;
        else
        {
            len++;
            arr = (double *)realloc(arr, sizeof(double) * len);
            arr[len - 1] = input;
            if (input > end)
                end = input;
        }
    }

    for (int i = 0; i < len; i++)
    {
        if (root(arr[i]) == 1)
            printf("yes\n");
        else
            printf("no\n");
    }

}

걍 무식하게 더블로 짰습니다...더블 짱짱맨

2015/08/17 14:22

조서현

import math
def light(n):
    div=0
    for i in range(1,n+1):
        if n%i==0:div+=1
    return True if div%2==1 else False

def light2(n):
    return math.sqrt(n) == int(math.sqrt(n))

def light3(n):
    return "yes" if math.sqrt(n)%1==0 else "no"

n=3
print light3(n)

2015/11/18 08:20

김 매미

def light(n):
    state = 0
    for i in range(1,int(n**0.5)+1):
        if n%i==0 : state^=1
    return ['yes','no'][state]

2016/01/24 19:59

상파

from itertools import accumulate
def mul(x, y):
    return x*y

def d(x):
    dic = {1:0}; i = 2
    while 1:
        if x%i == 0:
            x /= i
            try:
                dic[i] += 1
            except KeyError:
                dic[i] = 1
            i = 2
            continue
        if x<i:
            break
        i += 1
    return list(accumulate((dic[key]+1 for key in dic), mul))[-1]

while __name__ == '__main__':
    inpt = []; result = []
    while 1:
        inpt.append(int(input('>>>')))
        if inpt[-1] == 0:
            inpt.pop(len(inpt)-1)
            break
    for i in inpt:
        result.append(('no' if d(i)%2==0 else 'yes'))
    print('\n'.join(result))

소인수분해 했습니다. 파이썬 3.5.1

2016/04/15 00:26

Flair Sizz

처음 전구는 모두 꺼져있고 켜져있는 경우는 홀수번 누름. 즉, (약수의 개수가 홀수인 수)번째의 전구는 켜져있다는 것입니다.
우리가 알고있는(무르는 사람이 대부분일 수 있겠지만) 약수의 개수 구하는 법을 이용하면...
곱하여 홀수이므로 곱해진 수는 모두 홀수, 소인수분해했을때의 지수는 모두 짝수. 즉, 제.곱.수.

이 문제는 이 수가 제곱수인가 아닌가를 보는 문제이다.
import math
def light(n):
    return 'yes' if math.sqrt(n)%1==0 else 'no'
qu = []
while True:
    i = int(input())
    if i==0: break
    else: qu.append(i)
print('\n'.join(map(light,qu)))

2016/04/22 23:54

차우정

Python 3.4.4

import math
print("yes" if math.sqrt(int(input().split()[0])) % 1 == 0 else "no")

2016/05/13 14:31

SanghoSeo

def func31(n):
    if n == 0 : return
    lights = -1
    for i in range(n):
        if (n + 1) % (i+1) == 0 : lights *= -1
    result = ('','yes','no')
    print(result[lights])

꺼져있는 상태를 -1, 켜져있는 상태를 1로 간주하여 조건을 충족할때마다 -1을 곱하는 방식으로 하였습니다. 약수 생각은 전혀 못했네요, 또 배우고 갑니다 :)

2016/06/28 17:39

Park Jay

Ruby

is_on = ->num { num**0.5 % 1 > 0 ? "no" : "yes" }
chk_lights = proc { puts gets("0").chop.split.map(&:to_i).map &is_on }

Test

$stdin = StringIO.new("3\n6241\n8191\n0\n")
expect{ chk_lights.() }.to output( "no\nyes\nno\n" ).to_stdout

Output

chk_lights.()
3
6241
8191
0

no
yes
no

2016/07/04 19:17

rk

while True:
    n = int(input(":"))
    if n == 0:
        break
    flag = False
    for i in range(1, n + 1):
        if n % i == 0:
            flag = not flag
    print('yes' if flag else 'no')

Python 3.5.2에서 작성하였습니다.

다른분 풀이를 보고 다시 작성했습니다..

import math
while True:
    n = int(input(":"))
    if n == 0:
        break
    print('yes' if math.sqrt(n) % 1 == 0 else 'no')

2016/12/05 12:18

Yeo HyungGoo

def chk_light(num):
    val,count = 0,1
    while num != 0:
        val = count * count
        if val == num:
            return 'yes'
        elif val > num:
            return 'no'
        else:
            count += 1

_list = list()
while _list == [] or _list[-1] != 0:
    _list.append(int(input()))

for x in range(len(_list)-1):
    print(chk_light(_list[x]))

#### 2016.12.30 D-419 ####

2016/12/30 22:56

GunBang

#include <stdio.h>
#include <stdlib.h>

void main() {
    int n = 8191;
    int* arr = (int*) malloc (sizeof(int) * n);
    for(int i=0;i<n;i++)
        arr[i] = 0;

    for(int i=1;i<=n;i++) {
        for(int j=1;j<=n;j++) {
            if(j%i==0)
                arr[j-1] = arr[j-1]*-1 +1;
        }
    }
    if(arr[n-1]==1)
        printf("yes\n");
    else
        printf("no\n");
}

2017/01/12 16:31

코딩초보

def light_more(data):
    for i in data:
        if i!=0:
            print("yes" if sum(1 for j in range(1,i+1) if i%j==0)%2==1 else "no")
        else:
            return
light_more([3, 6241, 8191, 0])

2017/02/19 23:42

김구경

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import static java.lang.System.in;

public class LightMoreLight {

    public static void main(String[] args) {
        Scanner sc = new Scanner(in);
        List<Long> l = new ArrayList();
        while (sc.hasNext()) {
            Long i = sc.nextLong();
            if (i == 0L) break;
            l.add(i);
        }

        for (Long i : l) {
            System.out.println(solved(i) % 2 == 1 ? "yes" : "no");
        }
    }

    private static int solved(Long i) {
        List<Long> l = new ArrayList();
        Long len = i;
        l.add(1L);
        l.add(i);
        for (Long j = 2L; j < len; j++) {
            if (i % j == 0L) {
                l.add(j);
                Long x = i / j;
                if(x != j) l.add(x);
                len = x - 1;
            }
        }
        return l.size();
    }
}

2017/03/21 11:14

genius.choi

public class Lightbulb {

    private static String f_lightbulb(long n) {
        String yes = "yes";
        String no = "no";
        if (n==0) return no;if (n==1) return yes;
        String i_status = yes;
        int i = 2;

        //반 이상부터는 나눠지는 숫자가 자기 자신밖에 없음.
        while (i<=n/2){
            if (n%i ==0){
                if (i_status==yes){
                    i_status = no;
                } else {
                    i_status = yes;
                }
            }
            i++;
        }

        //자기 자신일 때는 항상 스위치 토글됨. n=6714, i=6714
        if (i_status==yes){i_status = no;} 
        else {i_status = yes;}

        return i_status;
    }
    public static void main(String[] args) {
        System.out.println(f_lightbulb(3));
        System.out.println(f_lightbulb(6241));
        System.out.println(f_lightbulb(8191));
    }

}

2017/04/02 16:12

daybreak

from math import floor

N = int(input(">>>"))

switch_case = set(sum([[x, int(N/x)] for x in range(1, int(floor(N**0.5))+1) if N % x == 0], []))

if len(switch_case) % 2 == 0:
    print("no")
else:
    print("yes")


2017/05/16 17:45

Taewon Song

python 3.4 배수만큼 뛰며 bitwise inverting 시키면 됩니다.

def mabu_step(n):
    s = [0]*n
    for i in range(len(s)):
        for j in range(i,len(s),i+1):
            s[j] = ~s[j]
    if s[-1] == -1: print('yes')
    else: print('no')

lines = []
while True:
    line = input()
    if line != '0': lines.append(line)
    else: break

for x in lines:
    mabu_step(int(x))

추가: 약수가 홀수 즉, 완전제곱수여야만 꺼진다는 멋진 알고리즘. 역시 수학.

from math import sqrt, modf

def mabu_factor(n):
    frac, intg = modf(sqrt(n))
    if frac == 0: print('yes')
    else: print('no')

2017/06/03 03:35

예강효빠

num = 8191
nList = [x for x in range(1,int(num/2)+1) if num % x == 0] + [num]

if len(nList) %2 == 0:
    print('no')
else:
    print('yes')

2017/06/16 22:48

SPJung

javascript

// 최초 꺼진 상태였으므로 스위치가 홀수번 눌렸으면 켜 있다.
// 즉, n 의 약수의 개수가 홀수개면 된다.
// 약수의 개수는 소인수분해 후 (지수+1)들을 다 곱하는 것이므로
// 그 곱이 홀수이려면 (지수+1)이 다 홀수, 즉 지수가 다 짝수여야 한다.
// 이런 수는 모두 x^2 으로 나타낼 수 있으므로 
// 제곱수인지 아닌지를 판단하면 된다

var isOn = function (n) {
    return Number.isInteger(Math.sqrt(n))    
};

var input=
`3
6241
8191
0`;

var line = input.split("\n").map(v => parseInt(v));
for (n of line) {
    if (n === 0) break;
    console.log(isOn(n) ? "yes" : "no");
}

2017/06/22 16:37

funnystyle

from math import sqrt, floor

def lighton(n):
    sqr = sqrt(n);
    return sqr == floor(sqr)

2017/08/23 20:10

Noname

while True:
    a=input()
    if a=='0':break
    f=[]
    for i in range(1,int(a)+1):
        if int(a)%i==0:
            f.append(i)
    d=len(f)        
    if d%2==0:print('no')
    else:print('yes')

2017/12/07 17:22

강상욱

(1) 문제 그대로 구현

strn = raw_input("pick a number from 1 to 2^32-1. press 0 to quit: ")

n = int(strn)
light = n*[-1]
# -1: off 1:on
if n == 0:
    print "bye"
    exit
elif (n >= 1) and (n <= 2**32-1):
    for j in range(0,n):      # j-th switch
        for i in range(0,j+1):  # i-th round trip: if j<i, j%i != 0 in any case
            if ((j+1) % (i+1)) == 0:
                light[j] = light[j]*(-1)
    if light[n-1] == -1:
        print "no"
    elif light[n-1] == 1: 
        print "yes"
else:
    print "wrong number"

(2) 제곱수 사용 (Katherine 님 설명 참조)

strn = raw_input("pick a number from 1 to 2^32-1. press 0 to quit: ")

import math
n = int(strn)
if n == 0:
    print "bye"
    exit
elif (n >= 1) and (n <= 2**32-1):
    square=math.sqrt(n)
    if square % 1 == 0:
        print "yes"
    else:
        print "no"
else:
    print "wrong number"

2017/12/11 01:57

영이

def mabu(n):
    tmp=0
    for i in range(1,n+1):
        if not n%i: tmp=(tmp+1)%2
    return(bool(tmp))

A=[]
while True:
    tmp=int(input('where: '))
    if not tmp:
        break
    else:
        A.append(tmp)

for i in A:
    if mabu(i): print('yes')
    else: print('no')

2017/12/15 00:15

빗나감

sqrt ㅋㅋㅋㅋㅋ 새삼 제가 얼마나 컴퓨터에 의존하면서 작성하고 있었던건지 알게 되네요 - 빗나감, 2017/12/15 00:26

파이썬 3.6

  • 아이디어> 마지막 전구의 on/off 상태만을 확인하도록, 각 i값으로 n값이 나누어 떨어지는지 확인하여 light on/off 값을 변경하여 최종상태를 확인합니다.
def inputdata(datalist):
    data = int(input(""))
    if data == 0:
        print("\n")
        return
    datalist.append(data)
    inputdata(datalist)

def lightcheck(datalist):
    light = 0
    for n in datalist:
        for i in range(1,n+1):
            if n%i == 0:
                if light == 1: light = 0
                else: light = 1
        if light == 1: print('yes')
        else: print('No')
        light=0

if __name__ == "__main__":
    datalist =[]
    try:
        inputdata(datalist)
    except ValueError:
        print( "정수값을 입력해주세요" )

    lightcheck(datalist)
  • 결과값
3
6241
8191
0


No
yes
No

2018/01/07 18:29

justbegin

파이썬

n,x = int(input("숫자를 입력하세요")),1
for o in range(2,n):
       if n%o == 0:
              x *= -1
if x == 1:
       print("마지막 되수의 문은 닫혀있습니다")
else:
       print("마지막 되수의 문은 열려있습니다")

C언어 - 3번째

#include "stdafx.h"
int main() {
    int n, o = 1;
    scanf("%d", &n);
    for (int x = 2; x < n - 1; x++) {
        if (n%x == 0) {
            o *= -1;
        }
    }
    if (o == 1) {
        printf("마지막 죄수의 문은 닫혀 있습니다.");
    }
    else {
        printf("마지막 죄수의 문은 열려 있습니다.");
    }
    return 0;
}

2018/01/09 19:25

김영성

# 파이썬


def lml(n):
    for t in range(int(n**0.5)+1, 1, -1):
        if (t-1)**2 == n: return "yes"
    else: return "no"


while 1:
    input1 = input("전구 갯수 입력, 종료는 0: ")
    if input1 == "0": break
    else: print(lml(int(input1)))


2018/02/07 13:29

olclocr

import math


def light(n):
    if math.sqrt(n)%1 == 0:
        result = 'yes'
    else:
        result = 'no'
    return result


b = []
n = 1
while 1:
    n = int(input())
    if n == 0:
        break
    b.append(n)
for i in map(light, b):
    print(i)

2018/02/08 15:53

김동하

N=int(input("입력하려는 숫자의 갯수를 입력하세요 (0포함)\n"))
num_list=[]
for line in range(N):
    num=int(input())
    if num<0 or num>=pow(2,32):
        num=int(input("다시 입력하세요\n"))
    num_list.append(num)


flag_list=[]
for num in num_list[:-1]:
    flag=0
    for n in range(1,num+1):
        if num%n==0:
            flag+=1
        else:
            continue
    flag_list.append(flag%2)

for f in flag_list:
    if f==0:
        print('no')
    else:
        print('yes')


2018/02/18 20:38

D B

def Mabu(*n) :

    for i in n :
        if i == 0 :
            break
        else :

            count = 0

            for j in range(1,i+1) :
                if i%j == 0 :
                    count += 1
                else :
                    continue

        print ('on' if count%2 == 1 else 'off')


2018/03/08 16:46

박강민

import java.util.Scanner;

public class bulbCheck{
 public static void main(String[] args){
  Scanner sc = new Scanner(System.in);

  int j;

  for(j=0;j!=(-1);j++){
   System.out.println("전구는 몇 개인가요? (종료 시 0 입력)");
   int input = sc.nextInt();

   if(input ==0)
    break;
   else{
    int i, a = 0;

    for(i=0;i<input;i++){
     if(a==0 && input%(i+1)==0)
      a=1;
     else if(a==1 && input%(i+1)==0)
      a=0;
    }
   if(a==1)
    System.out.println("yes\n");
   else
    System.out.println("no\n");
   }
  }
 }
}

2018/03/28 20:32

배혜민

while True:
    a = input()
    if a == '0':
        break
    a = int(a)
    count = 0
    for i in range(a):
        if a % (i+1) == 0:
            count = count + 1
        else:
            continue
    if count % 2 == 0:
        print('no')
    else:
        print('yes')

2018/04/04 12:05

최성범

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class LightMoreLight {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc = new Scanner(System.in);

        List<String> resultList = new ArrayList<>();

        while(true){
            int number = sc.nextInt();
            if(number == 0){ // 0이면 반복문 나가기
                break;
            }

            int[] lightArray = new int[number+1];

            for(int i = 1; i <= number; i++){
                for(int j=1 ; j < lightArray.length; j++){
                    if(j % i == 0){
                        lightArray[j]++;
                    }
                }
            }

            resultList.add(lightArray[number] % 2 == 0 ? "no" : "yes");

        }
        for(String str : resultList){
            System.out.println(str);
        }
    }

}

2018/04/06 18:13

김태훈

python 입니다 ;

n = input('Enter the number of bulbs:')
light = False
for i in range(int(n)):
    th = i + 1
    if int(n) % (th) == 0:
        light = not light

if light:
    print('yes')
else:
    print('no')

2018/04/09 17:23

무명소졸

// Light More Light
package main

import "fmt"

// goMabu: 마지막 전구 상태 반환
func goMabu(num uint64) string {
    light := false
    var way uint64
    for way = 1; way <= num; way++ {
        if num%way == 0 {
            light = !light
        }
    }
    if light == false {
        return "no"
    } else {
        return "yes"
    }
}

func main() {
    var numLight uint64
    numLights := []uint64{}
    for {
        fmt.Scanln(&numLight)
        if numLight == 0 {
            break
        } else {
            numLights = append(numLights, numLight)
        }
    }
    for _, v := range numLights {
        fmt.Println(goMabu(v))
    }
}

2018/04/10 13:48

mohenjo

// 자바입니다
  public static void main(String[] args) throws Exception { 
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        while(true) {
            long cnt = Long.parseLong(br.readLine());
            if (cnt == 0) break;

            boolean isShine = false;
            for (int i=1; i<=cnt; i++) {
                if (cnt % i == 0)
                    isShine = !isShine;
            }
            System.out.println(isShine ? "yes" : "no");
        }
    }
// 추천 많이 받으신 분 진짜 수학 잘하시네요... 단순히 이렇게 하니까 큰숫자 들어가면 연산 디게 오래걸리네요

2018/05/06 01:00

정몽준

i번째 왕복했을 때 i가 자신의 약수이면 상태가 바뀌므로

n의 약수가 홀수개라면, 즉 n의 제곱근이 정수라면 결과적으로 상태가 바뀌어 'yes'가 되고

그렇지 않다면 'no'가 됩니다.

따라서 mabu함수에서 n이 어떤 정수의 제곱인지 확인하여 yes, no를 리턴한 뒤

while문을 통해 입력을 받아 for문을 통해 mabu함수를 실행시킨 뒤 결과를 출력합니다.

def mabu(n):
    if n**0.5 == int(n**0.5): return 'yes'
    else: return 'no'
answer = [1]
while answer[-1]:
    answer.append(int(input()))
del[answer[-1]], answer[0]
for run in answer:
    print(mabu(run))

2018/05/20 16:00

myyh2357

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import static java.lang.System.in;

public class LightMoreLight {

    public static void main(String[] args) {
        Scanner sc = new Scanner(in);
        List<Long> l = new ArrayList();
        while (sc.hasNext()) {
            Long i = sc.nextLong();
            if (i == 0L) break;
            l.add(i);
        }

        for (Long i : l) {
            System.out.println(solved(i) % 2 == 1 ? "yes" : "no");
        }
    }

    private static int solved(Long i) {
        List<Long> l = new ArrayList();
        Long len = i;
        l.add(1L);
        l.add(i);
        for (Long j = 2L; j < len; j++) {
            if (i % j == 0L) {
                l.add(j);
                Long x = i / j;
                if(x != j) l.add(x);
                len = x - 1;
            }
        }
        return l.size();
    }
}

2018/05/21 10:43

聂金鹏

import java.util.ArrayList;
import java.util.Scanner;

public class LightMoreLight {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        ArrayList<Integer> Num = new ArrayList<>();
        int k = 0;
        while (true) {
            Num.add(Integer.valueOf(sc.nextLine().trim()));
            if (Num.get(k++) == 0) {
                break;
            }
        }
        for (int j = 0; j < Num.size() - 1; j++) {
            int Count = 0;
            for (int i = 1; i < Num.get(j) + 1; i++) {
                if (Num.get(j) % i == 0) {
                    Count++;
                }
            }
            System.out.println(Count % 2 == 0 ? "no" : "yes");
        }
    }
}

2018/05/28 17:22

김지훈

while(True):
    n = int(input('n번째 전구...? '))
    if n == 0:
        break
    light = False
    for i in range(1,n+1):
        if n%i == 0:
            light = not light
    if light:
        print("yes")
    else:
        print("no")

2018/06/30 17:53

재즐보프

약수일때마다 온 오프
약수의 갯수가 짝수이면 no, 홀수면 yes
제곱근이 정수면 홀수

inv = []
while 1:
    inv.append(int(input()))
    if inv[-1] == 0:
        del inv[-1]
        break
for i in inv:
    if (i**0.5)%1 == 0: print('yes')
    else: print('no')

2018/07/09 22:03

Creator

마지막 스위치를 누른 횟수를 재었습니다.

def mabu(n):
    r = 0
    for i in range(1, n+1):
        if n % i == 0: r += 1
    if r % 2 == 1:
        r = 'on'
        return r
    else:
        r = 'off'
        return r

2018/08/26 11:40

김건우

C#

using System;

namespace CD042
{
    class Program
    {
        static void Main()
        {
            string result = string.Empty;
            while (true)
            {
                uint numLights = uint.Parse(Console.ReadLine());
                if (numLights == 0) { break; }
                result += Environment.NewLine + LastLightStatus(numLights);
            }
            Console.WriteLine(result);
        }

        static string LastLightStatus(uint numLights)
        {
            bool lightStatus = false;
            for (uint way = 1; way <= numLights; way++)
            {
                if (numLights % way == 0) { lightStatus = !lightStatus; }
            }
            return lightStatus == true ? "yes" : "no";
        }
    }
}

2018/09/07 11:12

mohenjo

f=int(input('숫자 입력: '))

def func(f):

    n=[False for i in range(f)]
    cnt=1
    while cnt <= f: #번..
        for i in range(1,len(n)+1):
            if i%cnt==0: 
                n[i-1] = not(n[i-1])
            else: pass        
        cnt+=1
    return "Yes" if n[-1] == True else "no"

print(func(f))

답은 나오긴하는데 넘 느리네유

2019/01/05 23:24

S.H

import java.util.ArrayList;
import java.util.Scanner;
public class files {
    public static void main(String[] args) 
    {
        Scanner sc =new Scanner(System.in);
        ArrayList<String> desc = new ArrayList<String>();

        int input;
        boolean last;

        do
        {
            System.out.println("전구가 몇개입니까?");
            input = sc.nextInt();

            last = false;
            for(int f1=1;f1<=input;f1++)
            {
                if(input % f1==0)
                {
                    last =!last;
                }
            }

            if(input!=0)
            {
                desc.add( last ? "불켜짐" : "꺼짐");
            }
        }while(input !=0);

        for(int f1=0;f1<desc.size();f1++)
        {
            System.out.println(desc.get(f1));
        }
    }
}

2019/01/15 09:38

김상협

bag = []
while True:
    n = int(input())
    if n > 2**32 -1:
        raise Exception("Too many lights")
    elif n == 0:
        break
    else:
        bag.append(n)

lastlight = 0
for j in bag:
    for i in range(1, j+1):
        if j % i == 0:
            lastlight += 1
        else:
            continue
    if lastlight % 2 != 0:
        print('yes')
    else:
        print('no')
    lastlight = 0

2019/01/25 16:11

D.H.

import math
def light(x):
    return "yes" if math.sqrt(x)==int(math.sqrt(x)) else "no"

for i in [3,6241,8191]:
    print(light(i))

2019/01/27 00:49

임정섭

light_list = []
onoff_list = []
onoff=False
while True:
    n = int(input())
    if n==0:
        break
    else:
        light_list.append(n)

    for j in range(1,n+1):
        if int(n) % j==0:
            onoff = not onoff
    if onoff==True:
        onoff_list.append('yes')
    else:
        onoff_list.append('no')
    onoff=False

for i in onoff_list:
    print(i)

2019/02/18 09:12

namespace codingdojang__
{
    class Program
    {
        static void Main(string[] args)
        {
            Light(3);
            Light(6241);
            Light(8191);
            Light(0);
        }
        static void Light(int n)
        {
            bool on_off = false;

            if (n == 0)
            {
                Environment.Exit(0);
            }

            for (int i = 1; i <= n; i++)
            {
                if (n % i == 0)
                {
                    on_off = !on_off;
                }
            }
            Console.WriteLine(on_off ? "yes" : "no");
        }
    }
}

2019/02/21 14:27

bat

def s(a):
    count=0
    a=int(input())
    for b in range(1,a+1):
        if a%b==0:
            count+=1
        else:
            pass
    if count%2==0:
        print('no')
    else:
        print('yes')
s(a)

2019/02/21 16:52

소요자재

# 약수의 개수가 짝수이면 마지막 전구의 상태는 no
# 약수의 개수가 홀수이면 마지막 전구의 상태는 yes

def n_yak(n):

  s = 0
  for i in range(1, n+1):
    if n % i == 0:
      s += 1

  if s % 2 == 0:
    return 'no'
  else:
    return 'yes'

print(list(map(n_yak, [3, 6241, 8191])))

2019/03/12 21:05

Gerrad kim

def Mabu():

    bulb_list = list()
    on_off_list = list()
    x=-1
    while 1:
        bulb_num = int(input("Number of bulbs : "))
        if bulb_num!=0: 
            on_off_counter = 0
            bulb_list.append(bulb_num)
            x+=1
            for y in range (1,bulb_list[x]+1):
                if bulb_list[x] % y == 0:
                    on_off_counter+=1
            if on_off_counter % 2 ==0:
                on_off_list.append("Off")
            elif on_off_counter % 2 ==1:
                on_off_list.append("On")
        if bulb_num == 0 :
            for a in range(len(on_off_list)):
                print(on_off_list[a])
            break




2019/04/08 10:28

박범수

import java.util.Scanner;

public class LightMoreLight {
    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        System.out.println("n값 입력 : ");
        int n = scanner.nextInt();
        int count = 1;

        for(int i = 1; i <= n; i++) {
            if(n % i == 0) count *= -1;
        }

        if(count == 1) System.out.println("no");
        else System.out.println("yes");
    }
}

2019/04/08 14:03

김동혁

def swc(a):
    if a==0:
        return 1
    else:
        return 0

nl=[]

while 1:
    nl.append(int(input()))
    if nl[len(nl)-1]==0:
        del nl[len(nl)-1]
        break


for q in range(len(nl)):
    st=[i*0 for i in range(nl[q])] 
    for i in range(nl[q]):  
        for j in range(nl[q]):
            if (j+1)%(i+1)==0:  
                st[j]=swc(st[j])

    if bool(st[len(st)-1])==True:
        print("yes")
    else:
        print("no")

문제를 있는 그대로 완전탐색법으로 풀어보았읍니다. 전구의 수가 적을경우, 답이 곧장 나오지만 1000 단위가 넘어가면 답을내는 속도가 눈에 보일정도로 느려져서 무언가 속도를 개선할 수 있지 않을까 하는 생각을 하게되었읍니다.

nl=[]

while 1:
    nl.append(int(input()))
    if nl[len(nl)-1]==0:
        del nl[len(nl)-1]
        break
ans=[]   
for q in range(len(nl)):
    yakusu=[]
    for i in range(1,nl[q]+1):
        if nl[q]%i==0:
            yakusu.append(i)
    ans.append(len(yakusu))

ekq=''
for i in ans:
    if i%2==1:
        ekq+='yes \n'
    else:
        ekq+='no \n'

print(ekq)

생각하여 보니, n개의 전구가 있는 복도를 n회 반복할 때 마지막 전구의 소등/점등은 i회차 일순의 i가 n의 약수일 경우 나누어 떨어지므로 그때에만 영향을 미친다는 사실을 깨닫고 코드를 고쳐보았더니 시간복잡도가 꽤 떨어져서 이전과는 현저히 빨라져 있음을 확인하였읍니다. 또한, 세세하지만 마지막에 답을 낼때 일일히 print함수를 호출하는것 보다는 ekq라는 하나의 문자열을 만들어서 모든 버퍼를 ekq에 싣고나서 단 한번의 print로 일괄 출력하도록 하여 print함수의 호출 시간을 줄여보았읍니다.

2019/05/04 14:02

암살자까마귀

bulb = [int(input('>>>'))]
bulb += [0]*(bulb[0])

for i in range(1, len(bulb)):
    for j in range(1, len(bulb)):
        if i*j<=bulb[0]: bulb[i*j] += 1
        else: break

if bulb[-1]%2==1: print('yes')
else: print('no')

아래는 마지막 전구 상태만 확인해보았습니다.

n = int(input('>>>')); s = 0

for i in range(1, n+1):
    if n%i == 0: s += 1

if s%2 == 1: print('yes')
else: print('no')

2019/06/03 14:37

이진형

light=False
result=[]
while True:
    n=int(input("입력: "))
    if n==0:
        break
    a=list(range(1,n+1))
    for i in a:
        if n%i==0:
            if light==False:
                light=True
            elif light==True:
                light=False
    result.append(light)
    light=False
for i in result:
    if i==True:
        print('yes')
    else:
        print('no')

2019/08/18 22:36

박재욱

def onOrOff(n):
    countAliquot = len([i for i in range(1, n+1) if n % i == 0])
    if countAliquot % 2 == 0 : return 'no'
    else : return 'yes'

print(list(map(onOrOff, [3, 6241, 8191])))

2019/10/08 15:49

Dreaming Pug

while True :
    n = int(input("전구 수를 넣으시오 : "))
    count = 0
    if n == 0:
        break
    for i in range(1,n+1):
        if n % i == 0:
            count += 1
    if count % 2 == 0:
        print("no")
    elif count %2 ==1 :
        print("yes")

2019/10/28 22:44

semipooh

import java.util.*;
public class LightMoreLight {

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
        ArrayList<Integer> nums = new ArrayList<Integer>();
        int n = 0;
        while(true) {
            n=scan.nextInt();
            if(n==0) {
                break;
            }
            else {
            nums.add(n);
        }
        }
        for(int j=0; j<nums.size(); j++) {
            int count = 0;
            for(int k=1; k<nums.get(j); k++) {
                if(Math.pow(k, 2)==nums.get(j)) {
                    System.out.println("Yes");
                    break;
                    }
                else {
                    count++;
                }
            }
            if(count==nums.get(j)-1) {
                System.out.println("No");
            }
        }
    }
}

2019/11/17 21:33

big Ko

import java.util.Scanner;

public class LightOnOff {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        boolean run = true;

        while(run) {
            System.out.print("정수를 입력하시오: ");
            int input = sc.nextInt();
            if(input == 0) { break; }

            int light =0;

            for(int i = 1; i<=input; i++) {                 //input번 시행
                if(light==0 && input % i == 0) {            //i로 나누어 떨어지며 꺼진경우
                    light = 1;      
                    } 
                else if (light==1 && input % i == 0) {      //i로 나누어 떨어지며 켜진경우
                    light = 0;
                }

            }
            if(light== 0) {
                System.out.println("no");
            } else {
                System.out.println("yes");
            }
        }
        sc.close();
    }

}

2020/02/12 00:27

김강민

import math

input_num = int(input())

if math.sqrt(input_num) % 1 == 0 :

    print ('yes')

else: 
    print("no")

2020/03/10 09:23

HyukHoon Kim

iv = -1

lamp = False

def click():
    global lamp
    if lamp == True :
        lamp = False
    else:
        lamp = True

def print_lamp():
    global lamp
    if lamp == True :
        print("yes")
    else:
        print("no")



while iv != 0 :
    lamp = False
    iv = int(input("전구의 갯수를 입력하시오: "))
    for i in range (1, iv+1):
        if iv % i == 0:
            click()
    print_lamp()

2020/03/19 02:50

뤼크

list_streetlight = []
while True:
    streetlight = int(input('복도의 등이 몇 개 인가요? '))
    if streetlight == 0: break
    list_streetlight.append(streetlight)

light_status = lambda light: 'yes' if (light**0.5).is_integer() else 'no'

for i in list_streetlight:
    print(light_status(i))

처음으로 다른 분들의 답과 같은 방향으로 풀게된 문제라서 기쁘네요 ^^;

1부터 복도등 개수만큼 반복하는 형태로 코딩하여 마지막 복도등의 on, off여부를 구하는 경우 복도등의 수가 2^32-1의 경우 결과가 바로 나오지 않습니다

이미 다른 분들이 내용 설명과 구현을 한것을 구한것 처럼....

복도 등의 스위치 상태가 바뀌는 경우는
복도 등 개수의 약수인 횟수에 왕복하는 경우이므로 복도등이 n개 있다고 하면 1(첫번째 왕복)과 n번째 왕복하는 경우는 모든 수의 공통 약수이므로 1회 왕복에서는 스위치가 켜지고 마지막 스위치에서는 스위치가 꺼지게됨 따라서 첫번째 왕복과 마지막 왕복 회수 내의 약수의 개수가 짝수면 마지막 등은 항상 꺼져있게되고 (예 복도등이 10개인경우- 1:on, 2:off, 5:on, 10:off) 홀수면 마지막 등이 켜져 있게됨

최종숫자가 자신의 제곱수(예: 121은 11의 제곱, 121의 약수는 1:on, 11:off, 121:on)인 경우만 마지막 복도등의 켜지게 되므로 복도등에 제곱근을 구해 그 수가 정수인 경우 마지막 복도등이 켜져있다고 출력하는 형태로 코딩해보았습니다

2020/04/06 00:52

잘해보자

#파이썬

n=int(input('n='))
if n>0 and n<(2**32)-1:  
    nn=[0]*n
    for i in range (1,n+1):
        for j in range (1,n+1):
            if j%i==0:
                if nn[j-1]==0:
                    nn[j-1]=1
                else:
                    nn[j-1]=0
if nn[n-1]==1:
    print ('yes')
else:
    print ('no')

2020/04/09 01:22

Buckshot

<결과> n=3 no n=6241 yes n=8191 no - Buckshot, 2020/04/09 01:22
n = list(map(int, [3, 6241, 8191, 0]))
output = []
for i in n:
    light = False
    for j in range(1, i+1):
        if i % j == 0:
            light = not light
    result = 'yes' if light is True else 'no'
    output.append(result)
print(output)

2020/04/15 23:16

Hwaseong Nam

n = int(input())
light = list(map(int,list("0".zfill(n))))
for i in range(0,n):
    for k in range(0,n):
        if (k+1)%(i+1) == 0:
            light[k] += 1     
        else:
            continue
if light[n-1]%2 == 1:
    print("yes")
else:
    print("no")

zfill을 이용해서 더하고, 홀수일 경우 불이 켜져있다는 식으로 코딩해보았습니다

2020/05/11 23:12

Money_Coding

number=int(input())
b=[]
for i in range(1,number+1):
    for j in range(1, number+1):
        if i*j==number:
            b.append(i)
            b.append(j)
if len(list(set(b)))%2==0:
    print('no')
else:
    print('yes')

2020/06/18 12:30

SREBP1c

func solution(input:UInt) -> Bool? {
    if input == 0 {
        return nil
    }
    var isOn:Bool = false
    for i in 1..<input+1 {
        if input%i == 0 {
            isOn = !isOn
        }
    }
    return isOn
}

2020/07/12 11:22

이한위

n=int(input("전구는 몇개 있습니까? "))

def Mabu (n) :
    if n==0 :
        print("프로그램을 종료합니다.")
    else :
        Jungu = list(range(1,n+1))
        Jungu[0]=0
        i=0
        while i<n :
            i+=1
            for k in range (1, n+1) :
                if k%i==0 :
                    if Jungu[k-1]>1 :
                        Jungu[k-1] = 1
                    elif Jungu[k-1] == 1 :
                        Jungu[k-1]=0
                    else  :
                        Jungu[k-1]=1
        if Jungu[-1] == 1 :
            print("yes")

        else :
            print("no")

        n = int(input("전구는 몇개 있습니까? "))
        Mabu(n)

Mabu(n)

2020/09/19 15:27

KangJin Moon

n = int(input())
ramp = {True:'yes', False:'no'}
state = False # off
for i in range(1, n+2):
  if n%i == 0:
    state = not(state)

print(ramp[state])

python3

2020/11/04 10:00

조현우

def light(n):
    light = [False for i in range(0, n)]
    for k in range(1, n + 1):  # k번째 왕복
        for i in range(1, n + 1):  # i번째 전구
            if i % k == 0:
                light[i - 1] = not(light[i - 1])
    print("yes" if light[len(light) - 1] else "no")


light(3)
light(6241)
light(8191)

2020/11/24 16:56

김우석

def yaksu(number):
    n = int(number)
    result = []
    for i in range(1, number+1):
        if n % i == 0:
            result.append(i)
    return result

def Mabu(n):
    light = []
    for i in range(int(n)):
        light.append(0)

    # print('initial state :', light)

    for j in range(1, int(n)+1):
        for k in yaksu(j):
            if light[k-1] == 0:
                light[k-1] = 1
                # print('{}th run result: {}'.format(j,light))
                continue
            elif light[k-1] == 1:
                light[k-1] = 0
                # print('{}th run result: {}'.format(j,light))
                continue
    return light

num = 3
print(Mabu(num))
if Mabu(num)[-1] == 1:
    print('{}th light is ON'.format(len(Mabu(num))))
else: print('{}th light is OFF'.format(len(Mabu(num))))   

2020/12/10 08:40

DSHIN

def Light_More_Light(number):

  if number==0:

    print("END")

  else:

    num=1

    for_answer=False

    while num<=number:

      if number%num==0:

        if for_answer==False:

          for_answer=True

        else:

          for_answer=False

      num+=1

    return for_answer

print(Light_More_Light(3))

print(Light_More_Light(6241))

print(Light_More_Light(8191))

print(Light_More_Light(0))

2020/12/16 16:28

전준혁

def ligth():
    import math
    n =int(input('숫자를 입력하세요. : '))
    while n!=0:
        print('yes' if math.sqrt(n)%1==0 else 'no')
        n = int(input("숫자를 입력하세요.: "))

2021/01/03 17:45

hankyu

while True:
    n = int(input())
    if(n == 0): break
    if((int(n**(0.5))) == (n**(0.5))): print("yes")
    else: print("no")

문제가 n개의 전구 중 n번째 있는 전구가 켜져있는지를 묻는거라 n의 약수에서 스위치에 영향이 간다고 생각했습니다. 약수의 개수는 제곱근이 있으면 홀수 아니면 짝수 이기에 약수의 개수로 on off판단을 했습니다.

2021/01/08 01:32

guma go

from math import sqrt

l = []

while True:
    n = int(input())
    if n == 0:
        break
    l.append(n)



def f(n):
    if int(sqrt(n)) == sqrt(n):
        print('yes')
    else:
        print('no')

for i in l:
    f(i)

2021/02/17 13:34

Ha

nList = []

# 0이 나올때 까지 n 값을 받는다.
while True:
    n = int(input("전구의 개수를 입력하세요 : "))
    if n == 0:
        break
    nList.append(n)

resultList = []

# x는 nList의 index
for x in range(len(nList)):
    result = False

    # n을 i로 나누고, 나누어 떨어진다면 result값을 반전시킴
    for i in range(1, nList[x]+1):
        if nList[x] % i == 0:
            result = not(result)

    # result값이 True면 "Yes"를, False면 "No"를 반환시킴
    if result:
        print("Yes")
    else:
        print("No")

2021/02/26 18:24

지누

def Light(n):
    LastNumber=0
    for i in range(1,n+1):
        if n%i==0:
            LastNumber+=1
    if LastNumber%2==1:
        print("yes")
    else:
        print('no')
Light(6241)

2^32승부터는 작동이안되네요 잘푸신분의 math.sqrt 감명깊게 봤습니다

2021/03/04 21:28

fox.j

def toggle_light(n):
    for j in n:
        light = False
        for i in range(1,j+1):
            if (int(j)%i == 0):
                light = not(light)
        if light == False:
            print("no")
        else:
            print("yes")

ilist = []
while True:
    a = int(input())
    if a == 0:
        break
    else:
        ilist.append(a)

toggle_light(ilist)

2021/05/01 11:53

최태호

import math
print('yes') if math.sqrt(int(input()))%1 == 0 else print('no')

2021/05/31 22:39

ss2663

#codingdojing_light++

# 문제를 간단하게 바꾸면, n번째 전구가 켜지는 지 꺼지는지만 생각하면 된다.
# i번째 왕복에 마지막 전구의 스위치를 누르려면, i가 n의 약수여야 한다.
# 즉, n의 약수의 개수가 홀수면 마지막 스위치는 on, 짝수면 off이다. 

n = int(input('n: '))

while n:

    divisor_list = [ i for i in range(1,n+1) if n%i == 0]

    print('yes') if len(divisor_list)%2 == 1 else print('no')

    n = int(input('n: '))

#end

2021/07/28 21:13

Jaeman Lee

Light More Light

n = input("정수를 입력하세요 : ") n = int(n) count = [] for i in range(1, n+1): if n % i == 0: count.append(i)

if len(count) % 2 == 0: print("no") else: print("yes")

2021/08/29 17:16

김동현

def lamp(n):
    s = False
    for i in range(1, n+1):
        if n == 0:
            s = False
        elif n%i == 0:
            s = not s

    if s == True:
        print("yes")
    else:
        print("no")

def check_lamps(inArray):
    for i in range(len(inArray)):
        if inArray[i] != '0':
            number = int(inArray[i])
            lamp(number)


if __name__ == '__main__':
    inArray = input().split()
    check_lamps(inArray)

2021/09/29 18:51

서현준

다음과 같은 아이디어로 풀었습니다.

  1. 전구 켜짐 -> n의 약수가 홀수
  2. n을 n의 두 약수의 곱(예: 6이면 1 * 6, 2 * 3)으로 나타내면
  3. n의 약수가 홀수 -> 중복 약수 있음
  4. 9의 경우, 1 * 9, 3 * 3으로 약수가 중복됨(n이 제곱수)
  5. 전구 켜짐 -> n이 제곱수

소스 코드입니다.

data = []
while True:
    num = int(input())
    if not num: break
    data.append(num)

for item in data:
    print('yes' if item ** 0.5 == int(item ** 0.5) else 'no')

결과입니다.

3
6241
8191
1
4294967295
12
11
15
16
2147483647
3600
3969
6400
0
no
yes
no
yes
no
no
no
no
yes
no
yes
yes
yes

2021/10/03 21:07

이준우

while(true) { System.out.print("전구의 갯수는?: ");

    Scanner sc = new Scanner(System.in);
    int n=sc.nextInt();

    int count=0;// true, false
    boolean light;
    for(int i =1; i<=n ; i++) {
        if(n%i==0) {
            if(count==0) count=1;       
            else if(count==1) count=0;
        }
        if(count==1) light=true;
        else light =false;

        if(i==n) System.out.println(light); //마지막 전구 상태 출력
    }
    if(n==0) {
        System.out.print("종료합니다");
        break;
    }

    }

2021/10/28 20:01

초보자

arr =[]

def light_cnt(n) :
    light =-1
    for i in range(1,n+1) :
        if n%i == 0 :
            light *=-1
    return light

while True :
    n = int(input("전구의 개수를 입력해주세요"))
    arr.append(n)
    if n == 0 :
        break

result = list(map(light_cnt,arr))

for k in range(len(result)-1) :
    if result[k] == -1 :
        print("no")
    elif result[k] == 1 :
        print("yes")

2021/12/22 20:40

양캠부부

// Rust

// brute-force로 계산할수도 있으나, n번째 전등의 상태만 독립적으로 계산하는게 간편합니다.

fn main() {

let mut ns = vec![];
loop {
    let mut input = String::new();
    std::io::stdin().read_line(&mut input).expect("input error");
    let input = input.trim().parse::<usize>().unwrap();
    if input != 0 {
        ns.push(input);
        continue;
    }
    break;
}

// n번째 전등만 계산
for n in ns {
    let mut status = false; //n번째 전등의 상태
    for i in 1..=n {        //i번째 왕복
        if n % i == 0 {
            status = !status;
        }
    }
    println!("{}", status);
}

}

2022/01/27 11:06

JW KIM

sample = '''3
6241
8191
0'''

def lamp(a):
    count = 0

    for i in range(a):
        if a%(i+1) == 0:
            count = count +1

    if count % 2 == 0:
        return 'no'
    else:
        return 'yes'

for i in sample.split('\n'):
    if int(i) == 0:
        print()
    else:
        print(lamp(int(i)))

2022/02/08 16:56

로만가

문제는 제곱수냐 아니냐 의 문제는 이미 많은 분들이 풀어주셔서 문제를 바꿔 n개의 전구가 켜져있는지 꺼져있는지 모두 나타냈습니다.

n=400
bulbs={i:'no' for i in range(1,n+1)}

def turn(i):
    if bulbs[i]=='yes':
        bulbs[i]='no'
    elif bulbs[i]=='no':
        bulbs[i]='yes'

for i in bulbs:
    for times in range(1,n+1):
        if i*times<=n:
            turn(i*times)
        else:break

print(bulbs)

2022/03/10 21:12

코딩초보박영규

a = int(input())
for i in range(1,a+1):

    if a == 0:
        break
    elif a % i ==0:
        a+=1


if a%2==0:
    print('no')
elif a%2==1:
    print('yes')

2022/08/26 05:27

허명재

풀고나서 다른 분들 풀이 봤는데, 이 문제가 level2면 저렇게 처리속도를 생각하는 게 맞겠네요. 또 하나 배워갑니다

a = int(input())
switch = 0
for i in range(1,a+1):
    if a % i == 0:
        switch += 1
if switch % 2 == 0:
    print("No")
else:
    print("Yes")

2022/11/08 14:39

이웅기

JAVA입니다. 풀면서 약수 개수와 관련이 있을 것 같다는 생각은 했는데, 일일이 소인수분해를 할 생각만 하고 제곱수 여부만 따지면 된다는 생각은 못 했네요.

package question4.light_more_light;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        List<Boolean> states = new ArrayList<Boolean>();

        while(true) {
            int n = sc.nextInt();
            if(n == 0) break;

            boolean state = false; //false: 꺼짐, true: 켜짐
            for (int i = 1; i <= n; i++) {
                if(n%i == 0) {
                    state = !state;
                }
            }

            states.add(state);
        }

        sc.close();

        for (Boolean b : states) {
            System.out.println((b) ? "yes" : "no");
        }
    }
}

2025/02/22 22:28

박준우

목록으로