Есть 1000 лампочек и 1000 человек. Все лампочки изначально выключены. Человек 1 щелкает лампочкой 1, 2, 3, 4,… человек 2, затем переворачивает 2, 4, 6, 8,… человек 3, затем 3, 6, 9,… и т.д., пока все 1000 человек не сделают это. Каково состояние лампочек 25, 93, 576, 132, 605, 26, 45, 37, 36 после того, как все люди перевернули свои соответствующие лампочки? Есть ли общее решение для прогнозирования состояния лампочки? Сколько лампочек горят после того, как прошли 1000 человек?
Пояснение: Основные наблюдения:
Человек 1 щелкает лампочкой 1, 2, 3,… которые кратны 1.
Человек 2 щелкает лампочкой 2, 4, 6,… которые кратны 2.
Человек 3 щелкает лампочкой 3, 6, 9,… которые кратны 3.
Точно так же Человек 1000 переворачивает лампочку 1000, что кратно 1000.
Из приведенных выше наблюдений мы можем сказать, что человек i будет щелкать лампочки, кратные i,
Таким образом, лампочку j перевернут все люди, для которых j кратно их личному числу. Другими словами, лампочку j перевернут все люди, у которых для человека номер i является коэффициентом j,
Примеры:
(i) Лампочка 10 будет перевернута людьми 1, 2, 5, 10, чье количество людей кратно 10.
(ii) Лампочка 12 будет перевернута людьми 1, 2, 3, 4, 6, 12, чьи номера умножаются на 12.
Таким образом, лампочка 25 будет перевернута людьми 1, 5, 25, поэтому она будет перевернута 3 раза, что является странным, и поскольку изначально все лампочки были «выключены», теперь лампочка 25 будет «включена».
Лампочка 93 будет перевернута людьми 1, 3, 31, 93, поэтому она будет перевернута 4 раза, что является равным, и поскольку изначально все лампочки были «выключены», теперь лампочка 93 будет «выключена».
Лампочку 576 перевернут люди 1, 2, 3, 4, 6, 8, 9, 12, 16, 18, 24, 32, 36, 48, 64, 72, 96, 144, 192, 288, 576. , поэтому он будет перевернут 21 раз, что нечетно, поскольку изначально все лампочки были «выключены», теперь лампочка 576 будет «гореть».
Лампочка 132 будет перевернута людьми 1, 2, 3, 4, 6, 11, 12, 22, 33, 44, 66, 132, поэтому она будет перевернута 12 раз, что является равномерным, и поскольку изначально все лампочки были «выключены», теперь лампочка 132 будет «выключена».
Лампочка 605 будет перевернута людьми 1, 5, 11, 55, 121, 605, поэтому она будет перевернута 6 раз, что является равным, и поскольку изначально все лампочки были «выключены», теперь лампочка 605 будет «перевернута». выключенный".
Лампочка 26 будет перевернута людьми 1, 2, 13, 26, поэтому она будет перевернута 4 раза, что является равным, и поскольку изначально все лампочки были «выключены», теперь лампочка 26 будет «выключена».
Лампочка 45 будет перевернута людьми 1, 3, 5, 9, 15, 45, поэтому она будет перевернута 6 раз, что является равным, и поскольку изначально все лампочки были «выключены», теперь лампочка 45 будет «перевернута». выключенный".
Лампочка 37, являющаяся лампочкой с основным номером, будет перевернута людьми 1, 37, поэтому она будет перевернута 2 раза, что является равным, и поскольку изначально все лампочки были «выключены», теперь лампочка 37 будет «выключена». ».
Лампочка 36 будет перевернута людьми 1, 2, 3, 4, 6, 9, 12, 18, 36, поэтому она будет перевернута 9 раз, что нечетно, и, поскольку изначально все лампочки были «выключены», теперь лампочка 36 будет гореть.
Чтобы узнать состояние данной лампочки: Мы подсчитываем количество факторов числа лампочек, и согласно вышеприведенным наблюдениям, если количество факторов нечетное, то лампочка будет «включена», а если она четная, то она будет «выключена» в конец. Алгоритм определения количества лампочек, которые в итоге будут гореть: Мы подсчитываем множители каждого числа от 1 до 1000. Если число множителей для любого числа нечетное, соответствующая лампочка горит, поэтому мы обновляем результат и, наконец, печатаем его.
Ниже приведен код, реализующий описанный выше алгоритм.
C ++
// C++ implementation of above approach
#include <iostream>
usingnamespacestd;
intfindOnBulbs(intnumberOfBulbs)
{
// initializing the result
intonBulbs = 0;
// to loop over all bulbs from 1 to numberOfBulbs
intbulb = 1;
// to loop over persons to check whether their person number
intperson = 1;
// is a factor of light bulb number or not
for(bulb = 1; bulb <= numberOfBulbs; bulb++) {
// inner loop to find factors of given bulb
// to count the number of factors of a given bulb
intfactors = 0;
for(person = 1; person * person <= numberOfBulbs; person++) {
if(bulb % person == 0)// person is a factor
{
factors++;
// bulb != person*person
if(bulb / person != person)
{
factors++;
}
}
}
// if number of factors is odd, then the
if(factors % 2 == 1)
{
// light bulb will be "on" in the end
cout <<"Light bulb "
<< bulb
<<" will be on"
<<"
";
onBulbs++;
}
}
returnonBulbs;
}
// Driver program to test above function
intmain()
{
// total number of light bulbs
intnumberOfBulbs = 1000;
// to find number of on bulbs in
// the end after all persons have
// flipped the light bulbs
intonBulbs = findOnBulbs(numberOfBulbs);
cout <<"Total "
<< onBulbs
<<" light bulbs will be on in the end out of "
<< numberOfBulbs
<<" light bulbs"
<<"
";
return0;
}
Джава
// Java implementation of the
// above given approach
publicclassGFG
{
staticintfindOnBulbs(intnumberOfBulbs)
{
// initializing the result
intonBulbs =0;
// to loop over all bulbs from 1 to numberOfBulbs
intbulb =1;
// to loop over persons to check whether their person number
intperson =1;
// is a factor of light bulb number or not
for(bulb =1; bulb <= numberOfBulbs; bulb++) {
// inner loop to find factors of given bulb
// to count the number of factors of a given bulb
intfactors =0;
for(person =1; person * person <= numberOfBulbs; person++) {
if(bulb % person ==0)// person is a factor
{
factors++;
// bulb != person*person
if(bulb / person != person)
{
factors++;
}
}
}
// if number of factors is odd, then the
if(factors %2==1)
{
// light bulb will be "on" in the end
System.out.println("Light bulb "+ bulb +" will be on");
onBulbs++;
}
}
returnonBulbs;
}
// Driver program to test above function
publicstaticvoidmain(String [] args)
{
// total number of light bulbs
intnumberOfBulbs =1000;
// to find number of on bulbs in
// the end after all persons have
// flipped the light bulbs
intonBulbs = findOnBulbs(numberOfBulbs);
System.out.println("Total "+ onBulbs
+" light bulbs will be on in the end out of "
+ numberOfBulbs +" light bulbs");
}
// This code is contributed
// by Ryuga
}
Python3
# Python3 code implementing the
# given approach
deffindOnBulbs(numberOfBulbs):
# initializing the result
onBulbs=0
# to loop over all bulbs from
# 1 to numberOfBulbs
bulb=1
# to loop over persons to check
# whether their person number
person=1
# Is a factor of light bulb number or not
forbulbinrange(1, numberOfBulbs+1):
# inner loop to find factors of
# given bulb to count the number
# of factors of a given bulb
factors=0
forpersoninrange(1,int(numberOfBulbs**(0.5))+1):
ifbulb%person==0:# person is a factor
factors+=1
# bulb != person*person
ifbulb//person !=person:
factors+=1
# if number of factors is odd, then the
iffactors%2==1:
# light bulb will be "on" in the end
print("Light bulb", bulb,"will be on")
onBulbs+=1
returnonBulbs
# Driver Code
if__name__=="__main__":
# total number of light bulbs
numberOfBulbs=1000
# to find number of on bulbs in
# the end after all persons have
# flipped the light bulbs
onBulbs=findOnBulbs(numberOfBulbs)
print("Total", onBulbs,"light bulbs will",
"be on in the end out of",
numberOfBulbs,"light bulbs")
# This code is contributed
# by Rituraj Jain
C #
// C# implementation of above approach
usingSystem;
classGFG
{
staticintfindOnBulbs(intnumberOfBulbs)
{
// initializing the result
intonBulbs = 0;
// to loop over all bulbs from 1 to numberOfBulbs
intbulb = 1;
// to loop over persons to check whether their person number
intperson = 1;
// is a factor of light bulb number or not
for(bulb = 1; bulb <= numberOfBulbs; bulb++) {
// inner loop to find factors of given bulb
// to count the number of factors of a given bulb
intfactors = 0;
for(person = 1; person * person <= numberOfBulbs; person++) {
if(bulb % person == 0)// person is a factor
{
factors++;
// bulb != person*person
if(bulb / person != person)
{
factors++;
}
}
}
// if number of factors is odd, then the
if(factors % 2 == 1)
{
// light bulb will be "on" in the end
Console.WriteLine("Light bulb "+ bulb +" will be on");
onBulbs++;
}
}
returnonBulbs;
}
// Driver program to test above function
publicstaticvoidMain()
{
// total number of light bulbs
intnumberOfBulbs = 1000;
// to find number of on bulbs in
// the end after all persons have
// flipped the light bulbs
intonBulbs = findOnBulbs(numberOfBulbs);
Console.WriteLine("Total "+ onBulbs
+" light bulbs will be on in the end out of "
+ numberOfBulbs +" light bulbs");
}
}
// This code is contributed
// by Akanksha Rai
PHP
<?php
// PHP implementation of above approach
functionfindOnBulbs($numberOfBulbs)
{
// initializing the result
$onBulbs= 0;
// to loop over all bulbs from
// 1 to numberOfBulbs
$bulb= 1;
// to loop over persons to check
// whether their person number
$person= 1;
// is a factor of light bulb number or not
for($bulb= 1;
$bulb<=$numberOfBulbs;$bulb++)
{
// inner loop to find factors of given
// bulb to count the number of factors
// of a given bulb
$factors= 0;
for($person= 1;
$person*$person<=$numberOfBulbs;$person++)
{
if($bulb%$person== 0)// person is a factor
{
$factors++;
// bulb != person*person
if($bulb/$person!=$person)
{
$factors++;
}
}
}
// if number of factors is odd, then the
if($factors% 2 == 1)
{
// light bulb will be "on" in the end
echo"Light bulb ".$bulb.
" will be on"."
";
$onBulbs++;
}
}
return$onBulbs;
}
// Driver Code
// total number of light bulbs
$numberOfBulbs= 1000;
// to find number of on bulbs in
// the end after all persons have
// flipped the light bulbs
$onBulbs= findOnBulbs($numberOfBulbs);
echo"Total ".$onBulbs." light bulbs will ".
"be on in the end out of ".$numberOfBulbs.
" light bulbs"."
";
// This code is contributed by ita_c
?>
Javascript
<script>
// Javascript implementation of the
// above given approach
functionfindOnBulbs(numberOfBulbs)
{
// initializing the result
let onBulbs = 0;
// to loop over all bulbs from 1 to numberOfBulbs
let bulb = 1;
// to loop over persons to check whether their person number
let person = 1;
// is a factor of light bulb number or not
for(bulb = 1; bulb <= numberOfBulbs; bulb++) {
// inner loop to find factors of given bulb
// to count the number of factors of a given bulb
let factors = 0;
for(person = 1; person * person <= numberOfBulbs; person++) {
if(bulb % person == 0)// person is a factor
{
factors++;
// bulb != person*person
if(bulb / person != person)
{
factors++;
}
}
}
// if number of factors is odd, then the
if(factors % 2 == 1)
{
// light bulb will be "on" in the end
document.write("Light bulb "+ bulb +" will be on<br>");