Evil Science A whole load of stuff

4Sep/130

Use LINQ to calculate the Greatest Common Factor of a fraction

Want to calculate the Greatest Common Factor of fraction? Use this handy piece of LINQ:

int denom = 12;
int num = 8;
int gcf = Enumerable.Range(2, num - 1).LastOrDefault(i => num % i == 0 & denom % i == 0);

//gcf == 4

It returns a value of 0 if a GCF isn't found, hence the LastOrDefault.

It's straightforwards enough I think.

Comments (0) Trackbacks (0)

No comments yet.


Leave a comment

No trackbacks yet.