1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
| static class Extensions
{
public static string MultiplicationTable(this int number, int start = 0, int end = 10)
{
if (end < start) return number.MultiplicationTable(end, start);
// size of a number is floor (log10 (number)) + 1
// also log10 (a * b) = log10 (a) + log10 (b)
double lNumber = Math.Log10(Math.Abs(number));
double lEnd = Math.Log10(Math.Abs(end));
int lhsSize = (int)lEnd + 1;
int rhsSize = (int)lNumber + 1;
int resultSize = (int)(lEnd + lNumber) + 1;
// create the table format using xxxSize as width of the elements
string format = string.Format("{{0,{0}:N0}} * {{1,{1}:N0}} = {{2,{2}:N0}}\n", lhsSize, rhsSize, resultSize);
// starting from a new StringBuilder (~= an empty string)
// aggregate the values (starting at "start" till "end")
// and for each append a line to the StringBuilder
return Enumerable
.Range(start, end - start + 1)
.Aggregate(
new System.Text.StringBuilder(),
(stringBuilder, current) => stringBuilder.AppendFormat(format, current, number, current * number)
).ToString();
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine(42.MultiplicationTable());
}
}
// Output:
0 * 42 = 0
1 * 42 = 42
2 * 42 = 84
3 * 42 = 126
4 * 42 = 168
5 * 42 = 210
6 * 42 = 252
7 * 42 = 294
8 * 42 = 336
9 * 42 = 378
10 * 42 = 420 |
Partager