+ 1

Why does this problem print 2?

int[] a = {100,89,6,3}; for(int i=1;i<a.length;i++) a[i] = a[i-1] % a[i]; System.out.pritnln(a[3]);

23rd Oct 2019, 1:48 PM
Juan Debenedetti
Juan Debenedetti - avatar
4 Antworten
+ 4
you need previous value of a[3] & value of a[2] at that time, to calculate modified value of a[3] a[1]=a[0]%a[1]; //a[1]=100%89=11 a[2]=a[1]%a[2]; //a[2]=11%6=5 a[3]=a[2]%a[3]; //a[3]=5%3=2
23rd Oct 2019, 3:42 PM
Gaurav Agrawal
Gaurav Agrawal - avatar
+ 2
Let's look at it in details so that you understand it. Here's the original array: int[] a = {100,89,6,3}; first iteration i = 1 a[1] = a[1 - 1] = 100 % a[1] = 89 a[1] = 100 % 89 = result 100/89 = 1, remainder 11 new int array int[] a = {100,11,6,3}; Second iteration i = 2 a[2] = a[2 - 1] = 11 % a[2] = 6 a[2] = 11 % 6 = result 11/6 = 1, remainder 5 int[] a = {100,11,5,3}; Third iteration i = 3 a[3] = a[3 - 2] = 5 % a[3] = 3 a[3] = 5 % 3 = result 5/3 = 1, remainder 2 int[] a = {100,11,5,2}; int[] a = {100,11,5,2}; a[3] is 2 I recommend you run the code with some prints to help you understand it: for(int i = 1; i < a.Length; i++) { a[i] = a[i - 1] % a[i]; Console.WriteLine("Elements of a: {0}, {1}, {2}, {3}", a[0], a[1], a[2], a[3] ); Console.WriteLine(a[i]); }
23rd Oct 2019, 5:47 PM
Rodrigo Oliveira
Rodrigo Oliveira - avatar
+ 1
5 % 3 = 2
23rd Oct 2019, 2:17 PM
Tobias
Tobias - avatar
+ 1
@tobias 5?
23rd Oct 2019, 2:20 PM
Juan Debenedetti
Juan Debenedetti - avatar