2 ways in Java to add all the numbers below 1000 that are multiples of 3 or 5

This question is taken from Project Euler. Link

We will be showing you 2 solutions to this program:

  1. Simple but slow
  2. A little Complicated but fast
  • The Simple but Slow Program:

The logic used in the program is quite simple.

We have used two variables: sum and num. We initialize both sum and num to ’0′.

Next, we put the num in the while loop and keep incrementing num until it becomes 999(which is below 1000).

We have used a ‘If’ condition in the while loop. During the entire course, if num happens to be a multiple of 3 or 5, it will be added to the sum i.e sum=sum+num

Output: Output

  • The Complicated but Fast Program:

This program is a little complicated but faster as compared to the above one.

In this Program, We have used individual variables and functions for individual jobs:

  • class Functions to hold our individual functions.
  • int Num1Multiples and Num2Multiples to hold the sum of all multiples of Num1 (i.e. 3) and Num2 (i.e.5)
  • int CommonMultiples to hold the sum of all the common multiples of Num1 and Num2.
  • Function int addNaturalNum(int num): This function accepts 1 integer as argument and and calculates the sum of all the numbers from 1 to Num1
  • Function int GiveMeSum(int Num1, int Num2):This function accepts 2 integers as arguments (i.e. 3&5) and calculates the sum of all the multiples of those numbers.
    It uses the function addNaturalNum(999/Num1) to find the sum of all the multiples of Num1 from 1 to 999.

The program:


Thank you Goutam Chowdhury for this optimization.

Tested in Eclipse

The following two tabs change content below.

    I have another solution….
    We can make a function
    where m and n are given numbers.
    here m=3 and n=5;

    public int calMath(int m,int n)
    public int addNaturalNum(int num)
    return num(num+1)/2;

    suppose I want to add all the numbers below 20 that are multiples of 3 or 5
    1>Multiples of 3—3+9+12++15+18(total 6 numbers i,e 20/3=6)
    sum3Mul =3*sum of 6 natural number((n*n+1)/2)
    2>Multiples of 5–5++10+15+20(total 4 numbers i,e 20/5=4)
    sum3Mul =5*sum of 4 natural number((n*n+1)/2)
    3>Now numbers like 15 is duplicated
    so we need to minus

  • Vlad

    You are right Goutam, that’s another way to do it!