Skip to content

Instantly share code, notes, and snippets.

@vindia
Created August 27, 2015 10:32
Show Gist options
  • Save vindia/c70b6d24bbaeee046152 to your computer and use it in GitHub Desktop.
Save vindia/c70b6d24bbaeee046152 to your computer and use it in GitHub Desktop.
# Find the whole number _n_ that consists of 10 digits
# (e.g. 3451209876) for which the first _k_ digits
# can be divided by _k_ with `2 <= _k_ <= 9`
#
# Examples:
# The first 2 digits of _n_ can be divided by 2 (`34` => true)
# The first 3 digits of _n_ can be divided by 3 (`345` => true)
# The first 4 digits of _n_ can be divided by 4 (`3451` => false)
# etc.
#
# How many can you find?
def magic_number?(candidate)
return false if candidate.size < 10
return false if candidate.join.to_i % 10 != 0
return false if candidate[0,9].join.to_i % 9 != 0
return false if candidate[0,8].join.to_i % 8 != 0
return false if candidate[0,7].join.to_i % 7 != 0
return false if candidate[0,6].join.to_i % 6 != 0
return false if candidate[0,5].join.to_i % 5 != 0
return false if candidate[0,4].join.to_i % 4 != 0
return false if candidate[0,3].join.to_i % 3 != 0
return false if candidate[0,2].join.to_i % 2 != 0
true
end
(0..9).to_a.permutation.each do |candidate|
puts candidate.join.to_i if magic_number? candidate
end
@vindia
Copy link
Author

vindia commented Aug 27, 2015

This was written for a math assignment. I wonder if it can be made more efficient (both in terms of byte size and speed).

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