+ 2

[Solved] Code coach Divisible

What is the problem with this program? Case 3 is not passing. import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Program { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); int a = Integer.parseInt(reader.readLine()); String s = reader.readLine(); Divisible.div(a, s); } } class Divisible { public static void div(int a, String b) { String[] c = b.split(" "); int res = 0; for (int i = 0; i < c.length; i++) { if (Integer.parseInt(c[i]) == 0){ res++; } else if (a % Integer.parseInt(c[i]) == 0) { res += res; } else{ res++; } } if (res == 0) { System.out.println("divisible by all"); } else { System.out.println("not divisible by all"); } } }

10th Apr 2024, 2:22 PM
Suhani Kewat
5 odpowiedzi
+ 3
My minimalist Java solution, clears all tests. So you may have hit some sort of edge case that causes an error. Maybe there are no divisors or just one divisor in test 3. Or some value that is not a number and hence failing parseInt. SPOILER ALERT import java.util.Scanner; public class Divisible { public static void main(String[] args) { var sc = new Scanner(System.in); int n = sc.nextInt(); int rem = 0; while (sc.hasNextInt()) rem += n % sc.nextInt(); if (rem > 0) System.out.print("not "); System.out.print("divisible by all"); } }
10th Apr 2024, 6:40 PM
Tibor Santa
Tibor Santa - avatar
+ 2
At first sight your code looks correct (and it does work with the other cases), even though it is way too complex. If I change it to print always "divisible.." or always "not divisible.." at the end, it still fails for case 3 either way. Considering these are the only two valid outputs, my conclusion is that for this particular test case, the code reaches an exception and the result is never printed. Alternatively the Java test cases could be bugged. I will try to rewrite the code later and see how it works for my version.
10th Apr 2024, 3:14 PM
Tibor Santa
Tibor Santa - avatar
+ 2
Here is the corrected version of the program. I attached below! In the updated version of the program, the changes made include: 1. Fixed the calculation increment in the case where the number is divisible. Instead of `res += res;`, it is now `res++;`. 2. Added a condition to set `res` to -1 and break out of the loop as soon as a number is found that is not divisible. 3. Updated the condition to check if `res` is equal to 0 to determine whether the number is divisible by all inputs. https://sololearn.com/compiler-playground/cKGiflUc3EEh/?ref=app
10th Apr 2024, 8:07 PM
`ᴴᵗᵗየ
`ᴴᵗᵗየ - avatar
+ 2
Thank you, now this problem has been solved. This was very easy and small. There was no need for such a big program.
11th Apr 2024, 12:37 AM
Suhani Kewat
+ 1
Thanks for your efforts
10th Apr 2024, 3:47 PM
Suhani Kewat