Prefix and suffix Product

Source: Internet
Author: User

Description:

Give the series A1, A2,..., An, and set

Bi = (A1 * A2 * A3... An)/AI Mod (109 + 7)

Now we need to calculate all bi

Input:

The input contains multiple groups of test data. For each group of data, the length of the series is represented in 1st rows and 1 integer N (1 ≤ n ≤ 100,000. 2nd

Row, N integers A1, A2,..., an (1 ≤ AI ≤ 109), indicating the given series. The input end with a value of 0.

Output:

For each group of data, a row is output. N integers are separated by spaces, indicating the calculated b1, b2,..., bn.

Sample input:

3

1 2 3

0

Sample output:

6

3

2

 

Difficult to understand

The data given by the question is very big. If we continue to multiply, it will certainly overflow. So here we use a remainder allocation law (a * B) % C = (a % C * B % C) % C

However, this only produces A1 * a2...... an. Because there is no allocation rate in Division, prefix and suffix product are used to solve this problem.

That is, if n = 2, Bi = (A1 * A2 * A3 * A4 * A5) % AI => pre [I] = a1 % 1000000007 suff [I] = (A3 * A4 * A5) % 1000000007 Bi = pre [I] * suff [I]

The Code is as follows:

 

 1 #include<stdio.h> 2 #include<string.h> 3 #include<stdlib.h> 4 using namespace std; 5 long long a[100010],pre[100010],suff[100010]; 6 const int mod=1000000007; 7 int main() 8 { 9     int n,i;10     while(scanf("%d",&n)&&n)11     {12         memset(a,0,sizeof(a));13         for(i=1;i<=n;i++)14             scanf("%lld",&a[i]);15         pre[0]=1;16         for(i=1;i<=n;i++)17             pre[i]=(pre[i-1]*a[i])%mod;18         suff[n+1]=1;19         for(i=n;i>=1;i--)20             suff[i]=(suff[i+1]*a[i])%mod;21         for(i=1;i<=n;i++)22             printf("%lld%c",(pre[i-1]*suff[i+1])%mod,i==n?‘\n‘:‘ ‘);23     }24     return 0;25 }

 

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.