Two arrays a [N], B [N], where each element value of A [N] is known, and B [I] is assigned a value, B [I] = a [0] * a [1] * a [2]… * A [N-1]/a [I]
[Problem]
1. Division is not required.
Two arrays a [N], B [N], where each element value of A [N] is known, and B [I] is assigned a value, B [I] = a [0] * a [1] * a [2]... * a [N-1]/a [I]; requirements:
- 1. Division operations are not allowed.
- 2. Except for the cyclic Count value, a [N], B [N], no other variables (including local variables and global variables) are allowed)
- 3. time complexity O (n) and space complexity O (1 ). [Analysis]
Tip: Question B [I] = a [0] * a [1] * a [2]... * a [N-1]/a [I], equivalent to a [0] * a [1] * a [2] * a [3]... a [I-1] * a [I + 1] .. * a [N-1] is equivalent to removing the product of the current element a [I], all other elements (the left part of a [I], and the right part of a [I.
Note left [I] = semi a [k], (k = 1... i-1); right = clerk a [k], (k = I + 1... n) according to the description of B [I] = left [I] * right [I], initialize to 1 for each B [I, left [I] And right [I] can be multiplied by two times separately, that is, for the cyclic variable I = 1... n, B [I] = left [I]; B [n-I] = right [n-I]. The computation can be completed after the loop is completed.
[Code]#include
#include
void Multiplication(int *a, int *b, int length){int i;b[0] = 1;for (i = 1; i < length; i ++) {b[0] *= a[i - 1];b[i] = b[0];}b[0] = 1;for (i = length - 2; i > 0; i--) {b[0] *= a[i + 1];b[i] *= b[0];}b[0] = a[1] * b[0];}int main(void) {int i;int a[] = {2, 2, 3, 4, 5};int b[5];int length = sizeof(a) / sizeof(int);Multiplication(a, b, length);for (i = 0; i < length; i++)printf("%d\t", b[i]);return 0;}