Skip to content

Instantly share code, notes, and snippets.

@nothingrealhappen
Created March 31, 2015 12:12
Show Gist options
  • Save nothingrealhappen/a9ed4a1f89ee957d119b to your computer and use it in GitHub Desktop.
Save nothingrealhappen/a9ed4a1f89ee957d119b to your computer and use it in GitHub Desktop.
大厅里有100盏灯,每盏灯都编了号码,分别为1-100。每盏灯由一个开关来控制。(开关按一下,灯亮,再按一下灯灭。开关的编号与被控制的灯相同。)开始时,灯是全灭的。现在按照以下规则按动开关。
第一次,将所有的灯点亮。
第二次,将所有2的倍数的开关按一下。
第三次,将所有3的倍数的开关按一下。
以此类推。第N次,将所有N的倍数的开关按一下。
问第N次(N大于等于2,且小于等于100)按完以后,大厅里还有几盏灯是亮的。
请编程实现上面的逻辑,以N为参数
@Zkuns
Copy link

Zkuns commented Mar 31, 2015

def cool(n, array)
  return array if n == 0
  (1..100).each do |i|
    key = i * n
    next if key > 100
    array.include?(key) ? (array.delete(key)) : (array << key)
  end
  cool(n-1, array)
end
puts cool(55, []).size

@cloudy9101
Copy link

  def turn(n)
    arr = Array.new(100, 0)
    (1..n).each do |x|
      (0..99).each do |i|
        if (i+1) % x == 0
          arr[i] == 1 ? arr[i] = 0 : arr[i] = 1
        end
      end
    end
    puts arr.select{|i| i == 1}.count
  end

@nothingrealhappen
Copy link
Author

var light = [],
    size = 100,
    input = process.argv[2],
    count = 0;

for (var i = 0; i <= input; i++) {
  loop(function(j) {
    if(j%i === 0) switcher(j);
  });
}

function loop (fun) {
  for(var i=1; i <= size; i++) fun(i);
}

function switcher (i) {
  light[i] = !light[i];
}

loop(function(i) {
  if(light[i]) count ++;
});

console.log('第' + input + '次后还有' + count + '灯亮着.');

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment