Created
February 23, 2018 20:14
-
-
Save amit/dd16eff0ceb8031b1478cf2a8c487240 to your computer and use it in GitHub Desktop.
Find Harshad Numbers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Harshad numbers are divisible by sum of their digits. e.g. 1729 (1+7+2+9=19 and 19*91=1729 | |
# https://en.wikipedia.org/wiki/Harshad_number | |
# Sum of digits of a (positive) number: q | |
q = 987654321 | |
puts q.to_s.split('').reduce{|sum, n| sum.to_i + n.to_i}.to_i | |
# Find Harshad number between 1 and 1000: | |
puts (1..1000).select{|q| q % q.to_s.split('').reduce{|sum, n| sum.to_i + n.to_i}.to_i == 0} | |
# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 18, 20, 21, 24, 27, 30, 36, 40, 42, 45, 48, 50, 54, 60, 63, 70, 72, 80, 81, 84, 90, 100, 102, 108, 110, 111, 112, 114, 117, 120, 126, 132, 133, 135, 140, 144, 150, 152, 153, 156, 162, 171, 180, 190, 192, 195, 198, 200, 201, 204, 207, 209, 210, 216, 220, 222, 224, 225, 228, 230, 234, 240, 243, 247, 252, 261, 264, 266, 270, 280, 285, 288, 300, 306, 308, 312, 315, 320, 322, 324, 330, 333, 336, 342, 351, 360, 364, 370, 372, 375, 378, 392, 396, 399, 400, 402, 405, 407, 408, 410, 414, 420, 423, 432, 440, 441, 444, 448, 450, 460, 465, 468, 476, 480, 481, 486, 500, 504, 506, 510, 511, 512, 513, 516, 518, 522, 531, 540, 550, 552, 555, 558, 576, 588, 592, 594, 600, 603, 605, 612, 621, 624, 629, 630, 640, 644, 645, 648, 660, 666, 684, 690, 700, 702, 704, 711, 715, 720, 730, 732, 735, 736, 738, 756, 770, 774, 777, 780, 782, 792, 800, 801, 803, 804, 810, 820, 825, 828, 832, 840, 846, 864, 870, 874, 880, 882, 888, 900, 902, 910, 912, 915, 918, 935, 936, 954, 960, 966, 972, 990, 999, 1000] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment