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
Code:

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.

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

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

    then
    public int calMath(int m,int n)
    {
    return(m*addNaturalNum(1000/m)+n*addNaturalNum(1000/n)-m*n(addNaturalNum(1000/(m*n))));
    }
    public int addNaturalNum(int num)
    {
    return num(num+1)/2;
    }

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

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">