+ 1

Can you help me with the code challenge Multiples

First, I have tried in the following way but the output was showing as "Terminated. Execution Timed Out": import java.util.Scanner; public class Program { public static void main(String[] args) { Scanner s = new Scanner(System.in); int x = s.nextInt(); int sum = 0; int i = 1; while(i<x) { if(i%3==0 || i%5==0) sum += i; } System.out.println(sum); } } Then, I have changed it little bit in other way round but the same thing happened again: import java.util.Scanner ; public class Program { public static void main(String[] args) { Scanner s = new Scanner(System.in); int x = s.nextInt(); int sum1 = 0; int sum2 = 0; int sum3 = 0; int i = 1; while(i<x) { if(i%3==0) { sum1 += i; } if(i%5==0) { sum2 += i; } if(i%3==0 && i%5==0) { sum3 += i; } } System.out.println(sum1 + sum2 - sum3); } } Please kindly suggest me what to do in this case.

22nd Nov 2022, 9:34 AM
Devishree
Devishree - avatar
2 Answers
+ 1
Devishree In your first example, you didn't enclose the if statement if (... ) { sum += i } and then increment the i in the while loop after the if statement finishes: i++ Since i is not increasing it never reaches x, it just stays equal to 1 and so times out.
22nd Nov 2022, 9:56 AM
Scott D
Scott D - avatar
+ 1
Ok,small silly mistake😅 Thank you for correcting. The code is working now.
22nd Nov 2022, 10:04 AM
Devishree
Devishree - avatar