Sum of numbers smaller than n that are multiples of 3 or 5

0

I need to write a program that receives input n and prints the sum of all numbers smaller than n and that are multiples of 3 or 5.

For this, I should only use the while-repeat structure and no data type as a set or list, as it is an exercise in an introductory programming course.

    
asked by anonymous 19.03.2016 / 13:11

1 answer

3

Focus on the fact that the expected output is a single number: the sum. A simple way to solve is to look at each candidate, from the smallest to the largest. If it fits the constraints, add it to a variable that contains the partial result. A pseudo-code that implements this idea:

Seja n um número inteiro
Leia n
Seja soma um inteiro com valor 0
Seja i um inteiro com valor 1

Enquanto i for menor do que n:
    Se i é divisível por 3 ou i é divisível por 5:
        soma <- soma + i
    i <- i + 1

Imprima soma

There is room for optimizations. For example, is it necessary to look at even numbers? And the cousins? For the sake of simplicity, I've left that kind of thing out of the answer, but it's a good exercise to think about it.

    
19.03.2016 / 13:50