.net - How to stop adding numbers that occur twice in C# -
so trying find answer question:
if list natural numbers below 10 multiples of 3 or 5, 3, 5, 6 , 9. sum of these multiples 23. find sum of multiples of 3 or 5 below 1000.
i using c# , have pretty idea of do, code keeps counting numbers occur twice (e.g. 15, 30) , know quickest/easiest way counteract that. have found far has been in different language sorry if seems relatively easy you. have far:
static void main(string[] args) { var result1 = 0; var result2 = 0; var result3 = 0; var uniqueints3 = new list<int>(); (var = 0; < 1000; += 3) { uniqueints3.add(i); result1 += i; } var uniqueints5 = new list<int>(); (var o = 0; o < 1000; o += 5) { uniqueints5.add(o); result2 += o; } result3 += result1 + result2; console.writeline(result3); console.readline(); } i love if explain me not sure @ point.
not efficient way, should work
var sum = 0; for(int i=0;i<1000;i++) { if(i%3==0||i%5==0) //checks if multiple of 3 or 5 sum+=i; // sums when it's multiple of 3 or 5 } it ommits situations multiple of 3 , 5. takes each number once.
one line linq way:
var sum = enumerable.range(3, 1000).sum(x => (x % 3 == 0 || x % 5 == 0) ? x : 0); fastest mathematical approach version:
var result = sumdivisbleby(3,999)+sumdivisbleby(5,999)-sumdivisbleby(15,999); private int sumdivisbleby(int n, int p) { return n*(p/n)*((p/n)+1)/2; } it calculates sum of numbers divisible 3 , 5 substracts sum of numbers divisible 15. explanation: http://www.wikihow.com/sum-the-integers-from-1-to-n
Comments
Post a Comment