Sum multiples of 3 and 5: Difference between revisions
→{{header|C#}}
Line 45:
=={{header|C#}}==
The following code is an <i>efficient</i> solution in that it does not iterate through the numbers 1 ... n - 1 in order to calculate the answer. <i>However</i>, in C# the ulong (64-bit unsigned integer) type is insufficient to store the whole result of the larger calculations such that even for n = 1E+10 the final result is incorrectly reported. This is effectively a binary overflow - the upper bits are truncated. If there were a 128-bit integer type available, this would be able to calculate the result for n = 1E+20. Changing all instances of ulong to double will present an <i>approximation</i> of the correct answer, but double precision numbers are inherently imprecise. Implementing a 128-bit integer type in this context may be considered out of scope of the problem at hand.
<lang csharp>
using System;
namespace RosettaCode
Line 59 ⟶ 54:
class Program
{
static void Main(
{
ulong[] candidates = { 1000, 100000, 10000000, 10000000000, 1000000000000000 };
foreach (ulong candidate in candidates)
{
ulong answer5
};▼
Console.WriteLine("The sum of numbers divisible by 3 or 5 between 1 and {0} is {1}", c, answer3 + answer5 - answer15);
Console.Write("Give n: ");▼
}
private static ulong GetSumOfNumbersDivisibleByN(ulong candidate, uint n)
{
ulong largest = candidate;
while (largest % n > 0)
largest--;
ulong totalCount = (largest / n);
ulong count = totalCount / 2;
bool unpairedNumberOnFoldLine = (totalCount % 2 == 1);
ulong pairSum = largest + n;
return count * pairSum + (unpairedNumberOnFoldLine ? pairSum / 2 : 0);
}
}
}
</lang>
{{out}}
The sum of numbers divisible by 3 or 5 between 1 and 999 is 233168
The sum of numbers divisible by 3 or 5 between 1 and 99999 is 2333316668
The sum of numbers divisible by 3 or 5 between 1 and 9999999 is 23333331666668
The sum of numbers divisible by 3 or 5 between 1 and 9999999999 is 4886589257957115052
The sum of numbers divisible by 3 or 5 between 1 and 999999999999999 is 12252500107296959148
=={{header|C++}}==
|