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

Asked

Viewed 211 times

0

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

For this, I must use only the while repeating structure and no data type as set or list, as it is an exercise of an introductory programming course.

  • 1

    Why my question was negative?

  • I took the liberty of simplifying your question to quote just the relevant part: the desired algorithm and the constraints. I also traded "multiples of 3 and 5" for "multiples of 3 or 5," which I think is what you really need. Otherwise, let me know.

  • I accept the edition.

  • I just corrected the title.

1 answer

3


Focus on the fact that the expected output is a single number: the sum. A simple way to solve it 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 primes? For simplicity’s sake, I left that sort of thing out of the answer, but it’s a good exercise to think about it.

  • Thank you very much Pablo! I’ll think about it for sure!

  • Not at all, @Guilhermesantanadesouza. Good studies!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.