Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * This class calculates the sum of all multiples of 3
- * or 5 less than 1000
- * @author Tewodros
- * @version 1
- */
- public class SumOfMultiplesOfThreeOrFive {
- public static void main (String[] args){
- int multiplesOfThree = 0;
- int multiplesOfFive = 0;
- int multiplesOfFifteen = 0;
- int sum = 0;
- int i = 1;
- //adding up all multiples of three first
- while (multiplesOfThree + 3 <1000) {
- multiplesOfThree = 3 * i;
- sum += multiplesOfThree;
- i++;
- }
- int j = 1;
- //then add all multiples of 5
- while (multiplesOfFive + 5 <1000) {
- multiplesOfFive = 5 * j;
- sum += multiplesOfFive;
- j++;
- }
- //remove the duplicate multiples
- int k = 1;
- while (multiplesOfFifteen + 15 <1000) {
- multiplesOfFifteen = 15 * k;
- sum -= multiplesOfFifteen;
- k++;
- }
- System.out.println("Sum = " + sum);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement