우리 학교에는 복도 불을 켜고 끄는 마부(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
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
파이썬 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])
파이썬입니다.
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님의 알고리즘을 조금 변형해 본것입니다.
while 1:
n = int(input().strip())
if n == 0:
break
print('yes' if n**0.5 % 1 == 0 else 'no')
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)
파이썬 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)
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()
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 }
Perl 캐서린님이 잘 풀이 해 놓으셨네요. 약수의 갯수는 각 소인수 승수 + 1의 곱과 같으니 제곱수만 체크하면 되죠.
while(<>){
exit 0 if $_==0;
$_==int(sqrt($_))**2?print"yes":print"no";
print"\n"
}
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)
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;
}
}
}
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)
Sub Main()
Dim input As Long = Val(Console.ReadLine)
Console.WriteLine(IIf((Math.Sqrt(input) Mod 1 = 0), "yes", "no"))
End Sub
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");
}
}
걍 무식하게 더블로 짰습니다...더블 짱짱맨
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)
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]
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
처음 전구는 모두 꺼져있고 켜져있는 경우는 홀수번 누름. 즉, (약수의 개수가 홀수인 수)번째의 전구는 켜져있다는 것입니다.
우리가 알고있는(무르는 사람이 대부분일 수 있겠지만) 약수의 개수 구하는 법을 이용하면...
곱하여 홀수이므로 곱해진 수는 모두 홀수, 소인수분해했을때의 지수는 모두 짝수. 즉, 제.곱.수.
이 문제는 이 수가 제곱수인가 아닌가를 보는 문제이다.
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)))
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을 곱하는 방식으로 하였습니다. 약수 생각은 전혀 못했네요, 또 배우고 갑니다 :)
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
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')
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 ####
#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");
}
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])
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();
}
}
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));
}
}
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")
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')
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')
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");
}
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')
(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"
파이썬 3.6
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
파이썬
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;
}
# 파이썬
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)))
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)
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')
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')
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");
}
}
}
}
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')
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);
}
}
}
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')
// 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))
}
}
// 자바입니다
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");
}
}
// 추천 많이 받으신 분 진짜 수학 잘하시네요... 단순히 이렇게 하니까 큰숫자 들어가면 연산 디게 오래걸리네요
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))
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();
}
}
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");
}
}
}
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")
약수일때마다 온 오프
약수의 갯수가 짝수이면 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')
마지막 스위치를 누른 횟수를 재었습니다.
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
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";
}
}
}
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))
답은 나오긴하는데 넘 느리네유
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));
}
}
}
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
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))
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)
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");
}
}
}
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)
# 약수의 개수가 짝수이면 마지막 전구의 상태는 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])))
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
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");
}
}
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함수의 호출 시간을 줄여보았읍니다.
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')
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')
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])))
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")
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");
}
}
}
}
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();
}
}
import math
input_num = int(input())
if math.sqrt(input_num) % 1 == 0 :
print ('yes')
else:
print("no")
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()
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)인 경우만 마지막 복도등의 켜지게 되므로 복도등에 제곱근을 구해 그 수가 정수인 경우 마지막 복도등이 켜져있다고 출력하는 형태로 코딩해보았습니다
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)
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을 이용해서 더하고, 홀수일 경우 불이 켜져있다는 식으로 코딩해보았습니다
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')
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
}
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)
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
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)
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))))
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))
def ligth():
import math
n =int(input('숫자를 입력하세요. : '))
while n!=0:
print('yes' if math.sqrt(n)%1==0 else 'no')
n = int(input("숫자를 입력하세요.: "))
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판단을 했습니다.
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)
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")
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 감명깊게 봤습니다
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)
#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
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")
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)
다음과 같은 아이디어로 풀었습니다.
소스 코드입니다.
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
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;
}
}
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")
// 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);
}
}
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)))
문제는 제곱수냐 아니냐 의 문제는 이미 많은 분들이 풀어주셔서 문제를 바꿔 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)
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')
풀고나서 다른 분들 풀이 봤는데, 이 문제가 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")
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");
}
}
}