Public Group

Archived

This topic is now archived and is closed to further replies.

GCF

This topic is 5821 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

Is there a C++ function that finds the GCF of two integers? If so what do I need to #include to use it? Thanks ahead of time.

Share on other sites
Not that I''ve ever seen, but it shouldn''t be too hard to write one (may not be too efficient though!)

Chris Z.
ZeroFX Interactive

Share on other sites
I''ll just have to write one. I know how, it will just be tedious.

What is GCF?

Share on other sites
GCF? You mean GCD, greatest common divisor?

It's something like this:
  // I didn't test this very much...int gcd(int x, int y){  if (x < y) std::swap(x, y);    while (y != 0) {    int t = x%y;    x = y;    y = t;  }  return x;}
EDIT:
And just for fun, here's some code that forces the compiler to calculate the GCD of two constants. There are no calculations at runtime
  #define gcd(x, y) (gcd_t<x,y>::value)template <int x, int y>struct gcd_t{  static const int next_x = y;  static const int next_y = x%y;  static const int guard = static_cast<int>(next_y != 0);  static const int value = (guard) ? (gcd_t<next_x*guard, next_y>::value)                                   : (next_x);};template <>struct gcd_t<0, 0>{  static const int value = 0;};

[edited by - Beer Hunter on October 18, 2002 5:17:08 AM]

1. 1
2. 2
3. 3
Rutin
18
4. 4
JoeJ
14
5. 5

• 14
• 10
• 23
• 9
• 47
• Forum Statistics

• Total Topics
632636
• Total Posts
3007572
• Who's Online (See full list)

There are no registered users currently online

×