Factors of an integer: Difference between revisions

Content added Content deleted
No edit summary
Line 1,577: Line 1,577:
(push factor lows)
(push factor lows)
(push quotient highs)))))</lang>
(push quotient highs)))))</lang>

=={{header|Crystal}}==
{{trans|Ruby}}
<lang ruby>struct Int
def factors() (1..self).select { |n| (self % n).zero? } end
end</lang>

As we only have to loop up to <math>\sqrt{n}</math>, we can write
<lang ruby>struct Int
def factors
f = [] of Int32
1.upto(Math.sqrt(self)).select { |i| (self % i).zero? }
.each { |i|
f << (self // i) unless i == (self // i)
f << i
}
f.sort
end
end</lang>

'''Tests:'''
<lang ruby>
[45, 53, 64].each {|n| puts "#{n} : #{n.factors}"}</lang>
{{out}}
<pre>
45 : [1, 3, 5, 9, 15, 45]
53 : [1, 53]
64 : [1, 2, 4, 8, 16, 32, 64]</pre>


=={{header|D}}==
=={{header|D}}==