GCD and LCM
Read two natural numbers and print their greatest common divisor and least common multiple. Write the method static long Gcd(long a, long b).
Example 1
Input
12 18Output
GCD = 6
LCM = 36Example 2
Input
7 5Output
GCD = 1
LCM = 35A method is a named part of a program that performs one task. Methods make a program shorter, prevent repeated code and make it easier to find errors. Here we look at static methods, which are called without an object; methods of objects come in the lesson about classes.
A method has a header (modifiers, return type, name, parameters) and a body in curly brackets. The return statement returns the result and ends the method. Method names are written with a capital first letter.
using System;
class Program
{
// static: the method belongs to the class and is called without an object
// int: the return type; (int x): a parameter
static int Square(int x)
{
return x * x;
}
// void: the method returns nothing, it just does something
static void Line(int length, char symbol)
{
Console.WriteLine(new string(symbol, length));
}
static void Main()
{
Line(20, '=');
for (int i = 1; i <= 4; i++)
Console.WriteLine($"{i} squared is {Square(i)}");
Line(20, '-');
Console.WriteLine($"3^2 + 4^2 = {Square(3) + Square(4)}");
}
}
When the method is called, the arguments (the actual values) are assigned to the parameters in order: in the call Line(20, '=') the parameter length gets 20, and symbol gets '='.
using System;
class Program
{
static bool IsPrime(int n)
{
if (n < 2) return false;
for (int d = 2; d * d <= n; d++)
if (n % d == 0) return false; // return ends the method immediately
return true;
}
static int DigitSum(int n)
{
int s = 0;
while (n > 0)
{
s += n % 10;
n /= 10;
}
return s;
}
static int Larger(int a, int b) => a > b ? a : b; // a one-line method (=>)
static void Main()
{
string[] parts = Console.ReadLine().Split(' ');
int a = int.Parse(parts[0]), b = int.Parse(parts[1]);
// primes in the interval whose digit sum is also prime
for (int x = a; x <= b; x++)
if (IsPrime(x) && IsPrime(DigitSum(x)))
Console.Write(x + " ");
Console.WriteLine();
Console.WriteLine($"The larger of {a} and {b} is {Larger(a, b)}");
}
}
A method that returns bool makes a condition readable: if (IsPrime(n)) reads like a sentence. A short method can be written on one line, after the => sign.
By default a method gets a copy of the argument's value, so changing the parameter does not affect the variable in the call. With ref the method works with the variable itself, and out lets a method return several results. The word ref or out is also written in the call.
using System;
class Program
{
static void Increase(int x)
{
x += 10; // only the copy changes
}
static void IncreaseRef(ref int x)
{
x += 10; // the variable from the call changes
}
static void MinMax(int[] array, out int min, out int max)
{
min = max = array[0]; // out parameters must be given a value
foreach (int v in array)
{
if (v < min) min = v;
if (v > max) max = v;
}
}
static void Main()
{
int a = 5;
Increase(a);
Console.WriteLine($"After Increase: {a}");
IncreaseRef(ref a);
Console.WriteLine($"After IncreaseRef: {a}");
MinMax(new[] { 7, -3, 12, 0 }, out int mn, out int mx);
Console.WriteLine($"min = {mn}, max = {mx}");
}
}
Now it is clear how int.TryParse(text, out int number) works: the method returns a bool and writes the number through an out parameter. With arrays and objects a method gets a copy of the reference, so changes to the elements of an array remain visible even without ref.
using System;
class Program
{
// overloading: the same name, different parameters
static double Area(double a) => a * a; // a square
static double Area(double a, double b) => a * b; // a rectangle
// a default parameter value
static string Greeting(string name, string language = "en") =>
language == "fr" ? $"Bonjour, {name}!" : $"Hello, {name}!";
// params: any number of arguments
static int Sum(params int[] numbers)
{
int s = 0;
foreach (int n in numbers) s += n;
return s;
}
static void Main()
{
Console.WriteLine(Area(4));
Console.WriteLine(Area(4, 2.5));
Console.WriteLine(Greeting("Anna"));
Console.WriteLine(Greeting("Anna", "fr"));
Console.WriteLine(Greeting(language: "fr", name: "Mark")); // named arguments
Console.WriteLine(Sum(1, 2, 3));
Console.WriteLine(Sum(10, 20, 30, 40));
Console.WriteLine(Sum());
}
}
The compiler chooses the method by the number and types of the arguments. Two methods cannot differ only in their return type.
A recursive method solves a task by calling itself for a smaller problem. It must have a base case that is solved without a new call – otherwise the program crashes with a StackOverflowException error.
using System;
class Program
{
static long Factorial(int n) => n <= 1 ? 1 : n * Factorial(n - 1);
static int Gcd(int a, int b) => b == 0 ? a : Gcd(b, a % b); // Euclid's algorithm
static string Binary(int n) => n < 2 ? n.ToString() : Binary(n / 2) + (n % 2);
static void Main()
{
Console.WriteLine($"10! = {Factorial(10)}");
Console.WriteLine($"GCD(84, 36) = {Gcd(84, 36)}");
Console.WriteLine($"37 in binary = {Binary(37)}");
}
}
More about recursion and about when a loop is better: Recursion.
Each task has an example, a hint and a solution. The solutions have been checked on the examples in the text.
Read two natural numbers and print their greatest common divisor and least common multiple. Write the method static long Gcd(long a, long b).
12 18GCD = 6
LCM = 367 5GCD = 1
LCM = 35The digital root of a number is obtained by adding its digits, then the digits of the sum, until a one-digit number is left (98765 → 35 → 8). Write the recursive methods DigitSum and DigitalRoot and print the digital root of the number read (the number fits in a long).
9876584931932Main method.void must return a value in every case – otherwise you get the error "not all code paths return a value".ref and out are written both in the method header and in the call.1. What does void mean in a method header?
2. A method changes the value of an int parameter (without ref). What happens to the variable in the call?
3. What is an out parameter for?
4. What must every recursive method have?