Reputation: 19
I'm trying to write a program to find the highest common factor(HCF) (or greatest common denominator) and lowest common multiple(LCM) of 2 input numbers.
The issue I have is that I'm trying to use the HCF as part of my calculation to find the LCM, but am unable to store it properly into a separate variable. Code is below; the problem part that I know is the issue is right at the very end but I don't know the workaround. Any advice would be much appreciated, thanks.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ExerciseD
{
class Question2
{
static void Main()
{
Console.WriteLine("Please enter a number A: ");
double A = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Please enter a number B: ");
double B = Convert.ToDouble(Console.ReadLine());
double X = 0;
while (A > B)
{
A = A - B;
while (B > A)
{
B = B - A;
}
}
while (B > A)
{
B = B - A;
while (A > B)
{
A = A - B;
}
}
if (A == B)
{
Console.WriteLine($"The HCF of A and B is: {A}");
X = A;
Console.WriteLine($"The LCM of A and B is: {A * B / X}");
}
}
}
}
Upvotes: 0
Views: 748
Reputation: 792
Since your value of A
changes over time, save a copy of A
in another variable, say A2
, and use that in the final formula as A2 * B / X
.
Wait till you learn functions, that'll help organize your code better.
A shorter solution can be:
// Use temporary variables for backup
int tempA = A, tempB = B;
while (A != B) {
if (A > B) {
A = A - B;
} else {
B = B - A;
}
}
// Use dedicated variables for clarity
int HCF = A;
int LCM = (tempA * tempB) / HCF;
Console.WriteLine($"The HCF of A and B is: {HCF}");
Console.WriteLine($"The LCM of A and B is: {LCM}");
Functional Solution:
public int calcHCF(int A, int B) {
while (A != B) {
if (A > B) {
A = A - B;
} else {
B = B - A;
}
}
return A;
}
public int calcLCM(int A, int B) {
return (A * B) / calcHCF(A, B);
}
Main code:
Console.WriteLine("Please enter a number A: ");
int A = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Please enter a number B: ");
int B = Convert.ToDouble(Console.ReadLine());
Console.WriteLine($"The HCF of A and B is: {calcHCF(A, B)}");
Console.WriteLine($"The LCM of A and B is: {calcLCM(A, B)}");
Upvotes: 2