How to find the sum of all the multiples of 3 or 5 below 10 in C#

2 Answers

0 votes
using System;

public class Program
{
	public static void Main(string[] args)
	{
		int sum = 0;

		for (int i = 3; i < 10; i++) {
			if (i % 3 == 0 || i % 5 == 0) {
				Console.WriteLine(i);
				sum += i;
			}
		}

		Console.Write("sum = " + sum);
	}
}




/*
run:
  
3
5
6
9
sum = 23
  
*/

 



answered Oct 11, 2023 by avibootz
0 votes
using System;
 
public class Program
{
    public static int Sum(int n) {
        return (n * (n + 1)) / 2;
    }
 
    public static void Main(string[] args)
    {
        int below10 = 9;
 
        int sum = 3 * Sum((int)(below10 / 3)) + 5 * Sum((int)(below10 / 5)) - (3 * 5) * Sum((int)(below10 / 15));
 
        Console.Write("sum = " + sum);
    }
}
 
 
 
 
/*
run:
   
sum = 23
   
*/

 



answered Oct 11, 2023 by avibootz
edited Oct 13, 2023 by avibootz

Related questions

2 answers 158 views
3 answers 187 views
2 answers 189 views
2 answers 146 views
2 answers 161 views
2 answers 139 views
...