Solved

# getting lowest and greatet common factors

Posted on 2011-10-03

Hi,

I think that this is an errata, but I want to check this with you guyz.

I have a method called HasComFactor() method to get the lowest and greatest common factors if they exist.

The original code is in the below.

However, I have a problem with

int max = x < y ? x : y;

I think that it should be

int max = x < y ? y : x;

For 3 and 21,

it cannot find the lcf and gcf with 'int max = x < y ? x : y;', so I think that this is an error.

Am I right?

class MyClass{

public bool HasComFactor(int x, int y, out int lcf, out int gcf)

{

int max = x < y ? x : y;

bool first = true;

lcf = 1;

gcf = 1;

// Find lcf and gcf

for (int i = 2; i < max/2 + 1; i++)

{

if(((y%i)==0) & ((x%i)==0))

{

if(first)

{

lcf = i;

first = false;

}

gcf = i;

}

}// for

if(lcf !=1)

return true;

else

return false;

}

}// MyClass

class demo{

static void Main()

{

MyClass ob = new MyClass();

int lcf, gcf;

if(ob.HasComFactor(3, 21, out lcf, out gcf))

{

Console.WriteLine("LCF of 3 and 21 is " + lcf);

Console.WriteLine("GCF of 3 and 21 is " + gcf);

}

else

Console.WriteLine("No common factor for 231, 105");

Console.Read();

}

}