# Trying to compare two numbers

Hey guys I’ve been trying to compare two numbers that have no decimal point. When the user types in a number like 100 and also a number like 70, it will divide the number evenly and only display the ones that don’t have a remainder. I’ve managed to get to that point, but cant seem to figure out how to use those numbers to compare against each other. I’m trying to compare the highest common numbers between the two numbers, so then I can use that number else where.

Here’s what I have so far…

``````  static void Main(string[] args)
{

decimal userInputToInt = decimal.Parse(userInput);

decimal userInputToInt2 = decimal.Parse(userInput2);

//                              100               70
for (int i = 1; i <= userInputToInt || i <= userInputToInt2; i++)
{

decimal x = userInputToInt / i;
decimal z = userInputToInt2 / i;

if (userInputToInt % i ==0 )
{

Console.WriteLine(x); // How can I compare whats in here (the x)...

}

if (userInputToInt2 % i == 0) // ...with whats in here (the z)
{

Console.WriteLine(z);
}

}

}
}
}
``````

Just my own guess, although you might waste a few nanosconds more per comparison than some better thought out solution :)… this is a slightly better than brute force way of doing it, but if the numbers aren’t ginormous and you aren’t doing this thousands of times, who cares?.

First, check if the numbers are equal… if so, you’re done already. If not, figure out which is bigger. Now, do your for loop, and find all the equally divisible numbers for it, and put it in an list. (i.e. your list would have 100, 50, 25, 20, 10, 5, 4, 2, 1 … if not mistaken)

Next, process the smaller number in a similar for loop, and for each round of the loop where you have no remainder, check and see if that value exists in the list… if so, you’ve found your highest common denominator.

(this is also possibly where someone else swoops in and says you/I are reinventing the wheel But I’m not aware of a function that calculates highest common denominator already - not sure if this one would work: BigInteger.GreatestCommonDivisor(BigInteger, BigInteger) Method (System.Numerics) | Microsoft Learn)

Do you want to compare when both have no remainder?
You could just do :

``````int test = 0;
if(userInputToInt % i ==0 ) {
++test;
// more code?
}
if(userInputToInt2 % i == 0) {
++test;
// more code?
}
if(test == 2) { /* compare x and z */ }
``````

Let me know if I got what you’re saying.

Are you trying to find the common factors of both values?

Here’s a basic implementation:

``````        public static int[] CommonFactorsOf(int m, int n)
{
List<int> arr = new List<int>();

int i = 0;
if (m < 0) m = -m;
if (n < 0) n = -n;

//make sure m is < n
if (m > n)
{
i = m;
m = n;
n = i;
}

//could be sped up by looping to sqrt(m), but then would have to do extra work to make sure duplicates don't occur
for (i = 1; i <= m; i++)
{
if ((m % i) == 0 && (n % i) == 0)
{
}
}

return arr.ToArray();
}
``````

There’s a lot more that could be done to speed it up though. Hence my comment about looping only to sqrt(m). But this would require making sure duplicates don’t occur, as well as getting the factor pairs for m and n of i, and then testing if those are factors of n and m.

Something like this (done naively real quick just now):

``````        public static int[] CommonFactorsOf(int m, int n)
{
int i = 0;
int j = 0;
if (m < 0) m = -m;
if (n < 0) n = -n;

if(m > n)
{
i = m;
m = n;
n = i;
}

var set = new HashSet<int>(); //ensures no duplicates

int r = (int)Math.Sqrt(m);
for(i = 1; i <= r; i++)
{
if((m % i) == 0 && (n % i) == 0)
{
j = m / i;
if ((n % j) == 0) set.Add(j);
j = n / i;
if ((m % j) == 0) set.Add(j);
}
}

int[] arr = System.Linq.Enumerable.ToArray(set);
System.Array.Sort(arr);
return arr;
}
``````

Doing this loop until sqrt dramatically reduces the number of loops for large numbers of m. A number like 10,000 would loop… 10,000 times in the former. But would only loop 100 in the ladder. Making up for the cost of converting the hashset to an array, and sorting it.

Meaning the two algorithms are comparable for small numbers, but dramatically faster for large.

Cant I just compare these two lists? If so How can I do that?

These two lists contain all the numbers I need that don’t have anything passed the decimal point. Now I want to compare these two lists to see which numbers from these two lists are the same. After that I want the biggest numbers that are the same from that.

Here’s what I have so far…

``````        static void Main(string[] args)
{

decimal userInputToInt = decimal.Parse(userInput);

decimal userInputToInt2 = decimal.Parse(userInput2);

List<decimal> animals = new List<decimal>();// Want to compare the numbers in this list...

List<decimal> animals2 = new List<decimal>();//...With this list

for (int i = 1; i   <= userInputToInt ;   i++)

{

decimal x   =   userInputToInt     /       i;

if (   userInputToInt    %     i     == 0  )
{

Console.WriteLine(animals[animals.Count -1]);

}

}

for (int j = 1; j <= userInputToInt2; j++)

{

decimal z   =   userInputToInt2   /    j;

if (userInputToInt2 % j == 0)
{

Console.WriteLine(animals2[animals2.Count - 1]);

}

}

}
}
}
``````

So you don’t even want all the common factors, you want the greatest common factor, or GCD (greatest common divisor):

Euclid’s algorithm for GCD:

``````        /// <summary>
/// Greatest Common Divisor using Euclid's algorithm
/// </summary>
/// <param name="m"></param>
/// <param name="n"></param>
/// <returns></returns>
/// <remarks></remarks>
public static int GCD(int m, int n)
{
int r = 0;

// make sure positive, GCD is always positive
if (m < 0) m = -m;
if (n < 0) n = -n;

// m must be >= n
if (m < n)
{
r = m;
m = n;
n = r;
}

// now start loop, loop is infinite... we will cancel out sooner or later
while (true)
{
r = m % n;
if (r == 0)
return n;
m = n;
n = r;
}
}
``````

algorithm explained:

I mean technically you could linq to Intersect the two collections, then order by descending, and get the first element:

Intersect:

OrderBy:

FirstOrDefault:

``````int result = animals1.Intersect(animals2).OrderByDescending().FirstOrDefault();
``````

BUT… The Euclid algorithm is far more efficient.

Also, why are you using ‘Decimal’???

I don’t know why I’m using decimal actually. Also how would I implement what you suggested into my code? What would the finished product look like?

You copy paste my function into your code… and then call GCD(userInputToInt, userInputToInt2). The result is your greatest common divisor/factor.

Of course, make sure that you’ve typed userInputToInt as an int, and not a decimal.

Sorry I’m pretty new to c# programming. Could you show me where I would put the code, where it fits in? Thank you

It’s a function/method, you put next to the other function/method:

``````    static void Main(string[] args)
{

int userInputToInt = int.Parse(userInput);

int userInputToInt2 = int.Parse(userInput2);

int gcd = GCD(userInputToInt, userInputToInt2);
Console.WriteLine("The GCD is: " + gcd.ToString());

}

/// <summary>
/// Greatest Common Divisor using Euclid's algorithm
/// </summary>
/// <param name="m"></param>
/// <param name="n"></param>
/// <returns></returns>
/// <remarks></remarks>
public static int GCD(int m, int n)
{
int r = 0;

// make sure positive, GCD is always positive
if (m < 0) m = -m;
if (n < 0) n = -n;

// m must be >= n
if (m < n)
{
r = m;
m = n;
n = r;
}

// now start loop, loop is infinite... we will cancel out sooner or later
while (true)
{
r = m % n;
if (r == 0)
return n;
m = n;
n = r;
}
}
``````

I advise… since this looks a lot like a math question you might get in a introduction programming course.

If this is for class… just handing in this code may be suspicious. You should definitely research Euclid’s algorithm, I supplied links to it, so that you can explain HOW this works. Otherwise you probably will get marked as possibly cheating.

Furthermore, after learning the algorithm, learn how my implementation of it in code actually performs said algorithm. What each step is for, and how it accomplishes it.

Like… what is this:

``````if (m < 0) m = -m;
``````

Why did I do this? What does this line of code result in? Why didn’t I use Math.Abs?

Or this:

``````if (m < n)
{
r = m;
m = n;
n = r;
}
``````

What is this doing? Why must it be done? Why did I recycle ‘r’?

Oh no this is not for a class, I’m trying to build random little projects to learn more about c#. But I feel like I don’t know where to turn when I get stuck like what happened here. Its seems like you didn’t even use lists to compare, I feel like I don’t know where to go to get what you’ve done. I need somewhere where I can learn how to get where you are.

Learning C# is one thing. Solving a problem using an algorithm is another thing.

Once you have an algorithm worked out, then it’s a matter of implementing it in your language of choice.

If you’re not familiar with C#, then I’d advise you to familiarize yourself with the basics of C# before you start tackling algorithms.

This would be a good place to start: Learn game development w/ Unity | Courses & tutorials in game design, VR, AR, & Real-time 3D | Unity Learn

Like I said, I linked to an explanation of the algorithm I used.

You should first learn the algorithm (without code), then compare that to my code to understand how I did it.

https://en.wikipedia.org/wiki/Euclidean_algorithm

Go through the algorithm, learn it.

Here’s a video of the algorithm:

Note, in this video the person is doing long division to find the remainder.

In my code I use the % (modulo) operator. Which is a short hand operator to get the remainder.

12 % 5 = 2, because 2 is the remainder of 12 / 5.

Here’s another great source of explaining the algorithm in terms of computers:
http://www.informit.com/articles/article.aspx?p=2221792

I read this yeaaarrs ago as my introduction to computer algorithms, still sits on my bookshelf:

Then when going through the code, try to answer those questions I brought up in my previous post. Try asking other questions… just read it line for line and ask “why did lordofduct do this here” and apply what you learn about the algorithm when doing it.

When you don’t know what a symbol or something means… do what my parents always said when I asked what a word meant “you know where the bookshelf is!”… welp, you know where google is.

Thank you good sir. I will study up on the info provided.