Given an array of array[N]
elements (integers). Suggest a linear (time О(n)
) algorithm that generates such an array at the output so that out[i]
is equal to the product of all elements of array[N]
, with the exception of array[i]
, and the division operator is prohibited.
10 answers
First, consider the product of the elements on the left. Then on the right. C code:
int t = 1; for (int i = 0; i < N; ++i) { out[i] = t; t *= array[i]; } t = 1; for (int i = N-1; i >= 0; --i) { out[i] *= t; t *= array[i]; }
First, fill out so that the product of all elements from (i + 1) -th to the last is stored in out [i]. This can be done in O (n) by running through the array from the end. Then we run over first, preserving the number before - the product of all elements of the array that lie before the current one. after - the product of all array elements lying after the current one, we get from out [i + 1]. The answer for the current element is after * before. Implementation in python:
array = [i for i in xrange(1, 10)] n = len(array) out = [v for v in array] for i in xrange(n - 2, -1): out[i] *= out[i + 1] before = out[0] out[0] = out[1] for i in xrange(1, n - 1): after = out[i + 1] out[i] = after * before before *= array[i] out[n - 1] = before
arr1 = new int[N]; arr1[0] = 1 for(int i = 1; i < N; i++) arr1[i] = arr1[i - 1] * array[i - 1]; arr2 = new int[N]; arr2[N - 1] = 1 for(int i = N - 2; i >= 0; i--) arr2[i] = arr2[i + 1] * array[i + 1]; for(int i = 0; i < N; i++) out[i] = arr1[i] * arr2[i];
Cool method with suffixes and prefixes ( novgosh
). Store in one array the suffixes in another prefix, and then everything is simple. Implementation on pascal
.
var a,suf,pref,out:array[0..1000] of longint; i,n:integer; begin {считываем размер массива} writeln('n='); readln(n); {считываем сам массив} for i:=1 to n do read(a[i]); pref[0]:=1; suf[n+1]:=1; {вычисляем префикс} for i:=1 to n do pref[i]:=a[i]*pref[i-1]; {вычисляем суффикс} for i:=n downto 1 do suf[i]:=a[i]*suf[i+1]; {вычисляем сам массив out} for i:=1 to n do out[i]:=pref[i-1]*suf[i+1]; {выводим массив out} for i:=1 to n do write(out[i],' '); readln; end.
I will bring the original solution as always:
int mul=1; for(int i=0; i<n; i++) mul*=array[i]; for(int i=0; i<n; i++) out[i]=mul*pow(array[i], -1); //Здесь нет оператора деления!
- ahaha slyly - Specter
First, count the works on all prefixes, then on all suffixes (Over O(n)
simply by the cycle suf[i] = i ? suf[i - 1] * array[i] : array[i]
). Then out[i]
is the product of the prefix, ending on the left, to the suffix starting on the right.
- @NovGosh, if not difficult, show a specific code! - Nicolas Chabanovsky ♦
Script on c #:
// объявление переменных int p = 1; int n; // определение размера массивов Console.Write("Введите N "); try { n = Convert.ToInt32(Console.ReadLine()); } catch { Console.WriteLine("Введите целое число!"); Console.ReadKey(); return; } // объявление массива array int[] array = new int[n]; int[] out_array = new int[n]; // заполнение массива array for (int i = 0; i < n; i++) { array[i] = i + 1; } // заполнение массива out_array for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i != j) p *= array[j]; } out_array[i] = p; p = 1; } // вывод на экран массива out_array for (int i = 0; i < n; i++) Console.WriteLine("out_array[{0}] = {1}" , i, out_array[i]); Console.ReadKey();
- this is O (n ^ 2) - Yura Ivanov
int m = 3; //индекс исключения int[] a; //наш массив int s = 1; //произведение a = new int[5]; a[0] = 1; a[1] = 2; a[2] = 3; a[3] = 4; a[4] = 5; for (int i = 0; i < m; i++) { s *= a[i]; } for (int i = m+1; i < a.Length; i++) { s *= a[i]; } Console.WriteLine(s.ToString());
Not sure I understood the required task correctly, but still.
$array = array(1, 5, 6, 2, 9, 10, 15, 2, 7, 31); // массив $out = array(); $i = 0; for($i = 0; $i < count($array); $i++) { if(!$out[$i]) $out[$i] = 1; foreach($array as $key => $value) if($i != $key) $out[$i] *= $value; }; echo $out[1]; // выведет произведение всех элементов массива, но не умножая на $array[1], результат 7030800
x = array[i] array[i] = 1 out[i] = ... // перемножаем элементы array[i] = x
- O (n ^ 2), no? - drdaeman