Reputation: 225
I have to print product of elements of array A mod 10^9+7
,there should N
elements in array and the constraints are 1<=N<=10^3
and 1<=A[i]<=10^3
.
The code I wrote
#include<stdio.h>
int main()
{
int N, pro = 1;
scanf("%i", &N);
int arr[N];
for (int i = 0; i<N; i++) {
scanf("%i", &arr[i]);
pro = (pro*arr[i]) % (1000000007);
}
printf("%i", pro);
}
gave wrong answer but when I replaced int arr[N]
to long int arr[N]
and changed its precision specifier to %li
it gave correct output.
My confusion is when the upper limit of array's elements is only 10^3
then why using long int worked and not just int
.
i am using 64 bit windows OS and the inputs which i am giving are 3 digit numbers
as array elements for example 568,253 etc without any 0 in beginning.
Upvotes: 1
Views: 568
Reputation: 914
Consider the case where N = 3 and A = [10^3,10^3,10^3]. After the second iteration, your product will be 10^9. In the third iteration, your product will be (10^9 * 10^3) % 1000000007. Before doing the modulo operation, the product would create integer overflow and hence the WA.
Upvotes: 1
Reputation: 300
The problem may be the result of the expression (pro*arr[i])
.
If we assume that the maximum value of pro
is 1000000006 due to the modulo, and the maximum value of arr[i]
is 10^3 as mentioned. So, this expression may take a value greater than a 32bit integer.
The other thing to look for is What the type of (pro * arr[i])
? :
The compiler answers this question by look to the operands of the expression, and will set the return type, for integer, as the greater type of them.
If you set arr[]
as an long int []
this expression will return a long integer, whereas, if you set arr[]
as an int
, it will return an int
and so it'll be wrong :
int * int -> int
int * long int -> long int
Upvotes: 1