0

I don't know why this output is 2? Could you guys help?

public class Main { public static void main(String[] args) { int[]a={100,89,6,3}; for(int i=1;i<a.length;i++){ a[i]=a[i-1]%a[i]; } System.out.println(a[3]); } }

30th Aug 2022, 1:38 PM
Killiam Chances
Killiam Chances - avatar
2 Answers
+ 2
You can put the code on sololearn playground and print out the values for each iteration of the loop so it is easier to understand what happens: https://code.sololearn.com/ceTVhn1FLgBm/?ref=app
30th Aug 2022, 2:07 PM
Lisa
Lisa - avatar
0
Killiam Chances See the formula and notice that the value at each index [i] depends on the value at the index before it [i-1]. Start with determining what is in a[1] and work forward until you reach i=3. When i=1: a[1] = a[1-1]%a[1] = a[0]%a[1] = 100%89 = 11 Now find what is in a[2]. a[2] = a[2-1]%a[2] = a[1]%a[2] = 11%6 = 5 Finally, see what gets filled in at a[3]. a[3] = a[3-1]%a[3] = a[2]%a[3] = 5%3 = 2
31st Aug 2022, 1:40 AM
Brian
Brian - avatar