Ruby, 57 (67 without Rational
) (-3 if run in IRB)
p((a=[*1..100]).product(a).map{|x|Rational *x}.uniq.size)
Output:
6087
Can be 3 less characters if run in IRB, because you can remove the p(
and )
.
Uses product
for the numerator and denominator getting process, and then uses Rational
for converting them to fractions. If you remove the .size
at the end, it prints all of the fractions instead of how many there are.
It seems like it might take a long time to run, but it's actually almost instantaneous.
Here's an example IRB session to explain how the code works a bit better:
irb(main):027:0> (a=[*1..5]).product(a)
=> [[1, 1], [1, 2], [1, 3], [1, 4], [1, 5], [2, 1], [2, 2], [2, 3], [2, 4], [2, 5], [3, 1], [3, 2], [3, 3], [3, 4], [3, 5], [4, 1], [4, 2], [4, 3], [4, 4], [4, 5], [5, 1], [5, 2], [5, 3], [5, 4], [5, 5]]
irb(main):028:0> Rational 1, 2
=> (1/2)
irb(main):029:0> Rational 2, 4
=> (1/2)
Rational *x
uses the "splat" operator to call the Rational
function with arguments given in the array x
. This "splat" is also used in [*1..100]
.
Here's an alternative that doesn't use Rational
, weighing in at 66 characters:
p((a=[*1..100]).product(a).map{|x,y|z=x.gcd y;[x/z,y/z]}.uniq.size)
The fraction simplification method is replaced with this:
z=x.gcd y;[x/z,y/z]
which divides the numberator and the denominator by their GCD (greatest common denominator), and then sticks them back in an array so that uniq
can work.
How on earth is this question voted negative? I like it. I just added a +1, bringing it back up to 0 from –1. – Todd Lehman – 2015-04-15T18:06:12.330
1"no floating point numbers or fraction types" - does that mean, anywhere in the program? – CompuChip – 2014-04-10T07:49:43.383
@CompuChip Yes. Other non-number types are allowed – qwr – 2014-04-10T18:55:28.157