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]

Source: Internet
Author: User

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;}
        
       


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.