Sum of multiples of 3 or 5

Asked

Viewed 8,998 times

5

I’m trying to build a program that finds and adds the multiples of 3 or 5 below 1000.

The problem is that is returning a result of the sum that does not match what I asked.

    package basicojava;

public class Multiplos {
    public static void main(String[] args) {
        int x = 3;
        int z = 5;
        int somax = 0;
        int somaz = 0;
        int res;

        for(int i = 1; i < 1000; i++) {
            if(x % i == 0) {
                somax = i + i;
            }
        }
        for(int i = 1; i < 1000; i++) {
            if(z % i == 0) {
                somaz = i + i;
            }
        }
        res = somax + somaz;

        System.out.println("A soma dos multiplos de 3 e 5 abaixo de 1000, é: " +res);

    }
}

The sum is returning 16.

  • Within the two ties, switch to somax += i + i; within the first and somaz += i + i;

  • There was a change. Before it returned 16, now it is returning 20.

  • Just a clarification. The objective of the program is to sum all multiples from 3 or 5 to 1000, correct?

  • Or is the goal of the program to sum all multiples between "3 and 5" up to 1000? haha

  • "If we list all the natural Numbers Below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of These multiples is 23. Find the sum of all the multiples of 3 or 5 Below 1000."

  • 1

    So it is 3 or 5. It’s because the way you wrote in the double interpretation question, as @acklay explained in his answer, and ends up generating a completely different answer.

  • Thanks for the correction. I hadn’t noticed that.

Show 2 more comments

6 answers

12

Solution using IntStream

From Java 8 you can use the class IntStream to do the loop loop work:

IntStream stream = IntStream.range(1, 1000);

The above code will generate a Stream representing all integers between 1 and 1000. To get the sum of the values that are multiples of 3 or 5, just filter through the multiples of 3 or 5 and add them up:

long result = stream.filter(value -> (value % 3 == 0 || value % 5 == 0)).sum();

Thus, the value of result shall be the sum of all multiples of 3 or 5 between 1 and 1000, 233.168.

See working on Ideone.


Mathematical solution

Another possible solution is to analyze the problem mathematically. If we consider the sum of all values that are multiples of 3, we have:

3 + 6 + 9 + 12 + ... + 993 + 996 + 999

If we put the term 3 in evidence, we get:

3 * (1 + 2 + 3 + 4 + ... + 331 + 332 + 333)

That is, the sum of all multiples of 3 between 1 and 1000 is the equivalent of three times the sum of all integers between 1 and 333, where 333 refers to the largest multiple of 3, less than 1000, divided by 3. And it is known that the sum of integers between 1 and X is worth:

1 + 2 + 3 + 4 + ... + X = X*(X+1)/2

Generalizing, we have that the sum of all multiples of n, between 1 and N, will be:

S(n) = n*(N/n)*(N/n + 1)/2

Therefore, the sum of all multiples of 3, between 1 and 999, will be:

S(n=3) = 3*(999/3)*(999/3 + 1)/2 = 166.833

Similarly, the sum of all multiples of 5, between 1 and 999, shall be:

S(n=5) = 5*(999/5)*(999/5 + 1)/2 = 99.500

However, the multiples of 15, which are multiples of 3 and 5, will be counted twice and, to obtain the desired value, one must subtract the sum of the multiples of 15, between 1 and 999:

S(n=15) = 15*(999/15)*(999/15 + 1)/2 = 33.165

Thus, the sum of all multiples of 3 or 5, between 1 and 999, will be:

S = 166.833 + 99.500 - 33.165
S = 233.168

Which is the desired result. In Java we can do so:

class Main {
  public static void main(String[] args) {

    int N = 1000;
    int result = sum(3, N-1) + sum(5, N-1) - sum(15, N-1);

    System.out.println(result);
  }

  public static int sum(int n, int N) {
      return n * (N/n) * (N/n + 1)/2;
  }
}

See working on Ideone.

  • 3

    This heart in the mathematical solution is just

  • How crazy this mathematical solution was. I would never think about it! haha

  • @Vítormartins is basically the proof of the sum of the elements of a finite arithmetic progression, I only left so because I thought it would be easier to understand for those who do not know so deep the mathematics.

12


According to this reply on Soen, there is a mistake in your logic. The correct one would be to divide the i for x or z to see if they are multiple, and add to the cumulative variables:

public static void main (String[] args) {
    int x = 3;
    int z = 5;
    int somax = 0;
    int somaz = 0;
    int res;

    for(int i = 1; i < 1000; i++) {
        if(i % x == 0) {
            somax += i;
        }
    }
    for(int i = 1; i < 1000; i++) {
        if(i % z == 0) {
            somaz += i;
        }
    }
    res = somax + somaz;

    System.out.println("A soma dos multiplos de 3 e 5 abaixo de 1000, é: " +res);
}

However, the above code will add three and five common multiples twice, as you are doing the sum in separate loops, which will affect the result.

Another way to do this by unifying everything in a loop and avoiding the mentioned problem is as below:

int x = 3;
int z = 5;
int res = 0;



for(int i = 0; i < 1000; i++){
    if(i % x == 0 || i % z == 0){
        res += i;
    }
}

System.out.println("A soma dos multiplos de 3 e 5 abaixo de 1000, é: " +res);

See an example with multiples up to 10 on ideone, whose result will be 23 (3+6+9+5=23).

  • I didn’t quite understand this operator "=+". Could you explain to me?

  • 1

    @Hardysec see if you can understand with this example: a += b is the same as a = a + b, you assign the value of the left to the sum of itself with the values of the right. Give a read on this link that explains better: http://www.javaprogressive.net/2012/08/java-operators

  • Do these operators only exist in java? Or some in other languages like C?

  • @Hardysec did you ever visit the link I suggested? They are from java, as you explain there. :)

  • Yes, I visited. I just wanted to know if there are equivalents to these in C, since I use it also to study logic.

  • @Hardysec does not know C, but these operators usually do the same thing in all languages. Sometimes there is a particularity in one or the other, but in java is more or less what I explained in the first comment.

  • 1

    @Hardysec, they also exist in C. I can tell you that in general, most languages accept +=

  • For the record, the final result of these two solutions are different the first sum of the multiples in common of both (Ex: 15, 30). While the second, by being in the same loop, does not add these values.

  • @Zulian no, both do the same thing, the first only separated by adding the sum of the multiples of each separately, whereas in the second the single loop already does this without needing 2 different variables of sum.

  • Running the code, the first solution returns the sum 266333. The second 233168.

  • It may not be clear, but in the first example, the common values are summed up two times, while in the second only one.

  • @Zulian OP did not make this clear, and the exercise on which he based also does not leave this set, so the two options can be certain.

  • I agree, but they are codes that differ in certain respects and the answer does not make that clear. Users may get confused thinking they do exactly the same thing and one is "optimizing" the other.

  • 1

    @Zulian added an observation.

Show 9 more comments

4

Just adding, everything depends on interpretation, where can go wrong.

In the question speaks

...multiples of 3 and 5 below 1000.

That is to say

i % 3 && i % 5

I would do in this wayideone:

 for(int i = 1; i < 1000; i++){
    result = (i % n1 == 0 && i % n2 == 0)? result += i : result;
 }

If multiple of 3 or 5 below 1000, this would result in a totally different result.

That is to say

i % 3 || i % 5

I would do in this wayideone:

 for(int i = 1; i < 1000; i++){
    result = (i % n1 == 0 || i % n2 == 0)? result += i : result;
 }

Obs.: The int I’m starting with 1 why add 0 is just like adding up to nothing.

  • hehehe, was solved with a simple grammar, exchange of E by OR in the author’s question rsrs

  • @Leocaracciolo do not know if noticed the edition and we comments, but it was quite a translation error of an existing problem. hueBr

1

The sum of multiple numbers of n is a sum of arithmetic progression with a ratio equal to n.

One way to reduce complexity from O(n) to O(1) is to use a formula for this sum,

soma_de_pa = (primeiro_elemento + enesimo_elemento) * n / 2;

In this way, the desired programme would be as follows: dude,

class Programa {
    public static void main(String []args){
        int primeiro_elemento = 0;

        int enesimo_elemento_multiplo_3 = 1000 - (1000 % 3);
        int enesimo_elemento_multiplo_5 = 1000 - (1000 % 5);
        int enesimo_elemento_multiplo_15 = 1000 - (1000 % 15);

        double n_multiplo_3 = Math.ceil(1000 / 3.0);
        double n_multiplo_5 = Math.ceil(1000 / 5.0);
        double n_multiplo_15 = Math.ceil(1000 / 15.0);

        double soma_multiplo_3 = (primeiro_elemento + enesimo_elemento_multiplo_3) * n_multiplo_3 / 2.0;
        double soma_multiplo_5 = (primeiro_elemento + enesimo_elemento_multiplo_5) * n_multiplo_5 / 2.0;
        double soma_multiplo_15 = (primeiro_elemento + enesimo_elemento_multiplo_15) * n_multiplo_15 / 2.0;

        // O total é a soma dos múltiplos de 3 mais a soma dos
        // múltiplos de 5, menos a soma dos múltiplos de 15, que
        // foi contabilizada duas vezes, nas duas primeiras parcelas.
        // (obrigado, Anderson Carlos Woss, pela dica!)
        double soma = soma_multiplo_3 + soma_multiplo_5 - soma_multiplo_15;

        System.out.println(soma_multiplo_3);
        System.out.println(soma_multiplo_5);
        System.out.println(soma_multiplo_15);
        System.out.println(soma);
    }
}

0

public class somaMultiplos {

    public static void main(String[] args) {
        int numeroTres = 3;
        int numeroCinco = 5;
        int somaMultiploTres = 0;
        int somaMultiploCinco = 0;
        int resultado = 0;

        for(int i = 0; i < 1000; i++) {
            if((i%numeroTres == 0)||(i%numeroCinco == 0))
                resultado += i;     

            if((i%numeroTres == 0)&&(i%numeroCinco == 0))
                resultado += i;
        }
        // vai haver momentos de existir número múltiplos de 3 e de 5 ao mesmo tempo 
        // e portanto o primeiro "if" não leva isso consideração 
        //o segundo "if" é justamente para somar os números que são múltiplos de 3 e 5 ao mesmo tempo


        System.out.println("A soma dos multiplos de 3 e 5 abaixo de 1000, é: " +resultado);
    }
}
  • 3

    I find it interesting to put an explanation out of the code, who glances thinks it’s just a bunch of code played on the screen

  • Mainly explain why the second exists if, if the number is multiple of 3 and 5, it will already be multiple of 3 or 5, entering the first if.

  • the idea is to add multiples of 3 and 5, the first "if" it will add to the result values that are multiples of 3 or 5, only for example the number 30 is multiple of 3 and 5 at the same time, then the 30 will be added only once to the result and, i believe it should be summed twice that is the function of the second "if"

0

I managed to solve my exercise by doing so:

//Some todos os numeros naturais abaixo de 1000 que são múltiplos de 5 ou 3.

public class Exerc25 {
    public static void main(String[] args) {

        //---------------variáveis
        int numero, soma = 0;
        Scanner teclado = new Scanner(System.in);

        //---------------Entrada de dados
        System.out.print("Digite um número (qualquer um, pode ser 1000): ");
        numero = teclado.nextInt();

        //---------------Processamento
        for(int i = numero-1; i >= 0; i--) {
            if(i % 5 == 0 | i % 3 == 0) {
                soma = soma + i;
            }
        }

        //---------------Impressão
        System.out.println("Soma: " + soma);

        teclado.close();
    }
}

thus the result is exactly 233,168 if you insert 1000 as input.

Browser other questions tagged

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