How to find the sum of all the multiples of 3 or 5 below 1000 in Pascal

2 Answers

0 votes
program SumOfMultiples;

var
  sum: Int64;
  i: Integer;

begin
  sum := 0;

  for i := 1 to 999 do
  begin
    if (i mod 3 = 0) or (i mod 5 = 0) then
    begin
      sum := sum + i;
    end;
  end;

  Writeln('The sum of all multiples of 3 or 5 below 1000 is: ', sum);
end.


(*
run:

The sum of all multiples of 3 or 5 below 1000 is: 233168

*)

 



answered Apr 14, 2025 by avibootz
edited Apr 14, 2025 by avibootz
0 votes
program SumMultiples;

var
  LIMIT: Integer;
  upper_for_three, upper_for_five, upper_for_fifteen: Integer;
  sum_three, sum_five, sum_fifteen, total_sum: Real;

begin
  LIMIT := 999;

  // Calculate the upper bounds
  upper_for_three := LIMIT div 3;
  upper_for_five := LIMIT div 5;
  upper_for_fifteen := LIMIT div 15;

  // Calculate the sums using the arithmetic series formula
  sum_three := 3 * upper_for_three * (1 + upper_for_three) / 2;
  sum_five := 5 * upper_for_five * (1 + upper_for_five) / 2;
  sum_fifteen := 15 * upper_for_fifteen * (1 + upper_for_fifteen) / 2;

  // Calculate the total sum
  total_sum := sum_three + sum_five - sum_fifteen;

  Writeln('The total sum is: ', Round(total_sum));
end.



(*
run:

The total sum is: 233168

*)

 



answered Apr 14, 2025 by avibootz
...