+ 1

Failing a test case - Simple loop and math question.

Here is the question: Create a function, that will for a given a, b, c, do the following: Add a to itself b times. Check if the result is divisible by c. Notes: In the first step of the function, a doesn't always refer to the original a. "if the result is divisible by c", means that if you divide the result and c, you will get an integer (5, and not 4.5314). The second test is correct. ------------------------------------------------------------------------------------------------------------- My code: public class Challenge { public static boolean abcmath(int a, int b, int c) { int sum = 0; for (int i = 0; i < b; i++){ sum += a; if (sum % c == 0) return true; } return false; } } Failing this unit test and can't figure out why: @Test public void test2() { assertEquals(false, Challenge.abcmath(69, 15, 9)); } As stated in the notes, second test is correct. Passes all other 7 tests. Any thoughts? TIA!!!

22nd Jul 2020, 5:05 PM
GG128
7 Antworten
22nd Jul 2020, 5:36 PM
Sandra Meyer
Sandra Meyer - avatar
+ 1
You never changed a and always only added the same a to the sum == a * b.
22nd Jul 2020, 5:37 PM
Sandra Meyer
Sandra Meyer - avatar
+ 1
Oh I see...Thanks so much for your help! : )
22nd Jul 2020, 5:46 PM
GG128
0
I guess you should check the modulo of c AFTER your loop...
22nd Jul 2020, 5:14 PM
Sandra Meyer
Sandra Meyer - avatar
0
Btw. the result of 69*15 is 1035 which is equal to 115*9, so the expected value in your test case is wrong.
22nd Jul 2020, 5:30 PM
Sandra Meyer
Sandra Meyer - avatar
0
Thanks for your reply Sandra. I will try divisibility after loop. It's not a * b, it's adding a to itself b times. Like this one abcmath(42, 5, 10) ➞ false // 42+42 = 84, 84+84 = 168, 168+168 = 336, 336+336 = 672, 672+672 = 1344 // 1344 is not divisible by 10
22nd Jul 2020, 5:33 PM
GG128
0
Then your loop content is wrong. You're calculating a * b.
22nd Jul 2020, 5:35 PM
Sandra Meyer
Sandra Meyer - avatar