-1

i was doing a CS homework, the question is to get n!, where n <=10^6, and to fit it, i need n! % m,

i wrote the following code:

#include <bits/stdc++.h>
using namespace std;

int main ()
{
long long n, m = 7+10e9, fact = 1;//value of m is given
cin>>n;
n++;

while (--n)
{
       fact = ((fact%m)*(n%m))%m;
       cout<<fact<<endl;//added this of debugging 
       if (fact == 0) break;//and this also

}
cout <<fact;
return 0;
}

the code is fine with small numbers (i.e < 10^5) however when the numbers get bigger the fact output is 0, after printing the fact in each step, i realized that when for some reason the fact(x) == fact (x-1) (x is the step), the new fact is zero

for example when i entered 10^6, the fact got 8478216162 two times successively, and then got zero.

any help is thanked in advance

1 Answers1

2

There are two mistakes in your code.

  1. m = 7+10^9 . Here ^means bitwise xor operator, not power. You should write it either m = 7 + 10e9 or m = 1000000007
  2. if (fact = 0) . When you give single equal then it is not checking. Rather than it is assigning fact value to 0. So write double equal. if (fact == 0)

Your full code should be like this -

#include <bits/stdc++.h>
using namespace std;

int main () {
    long long n, m = 7+10e9, fact = 1;//value of m is given
    cin>>n;
    n++;
    while (--n) {
        fact = ((fact%m)*(n%m))%m;
        //cout<<fact<<endl;//added this of debugging
        if (fact == 0)
            break;//and this also

    }
    cout <<fact;
    return 0;
}
Faruk Hossain
  • 1,135
  • 3
  • 11
  • 4
    I think you should add that use of [`#include `](https://stackoverflow.com/Questions/31816095/Why-Should-I-Not-Include-Bits-Stdc-H) and [`using namespace std;`](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) are discouraged. – Jaideep Shekhar Dec 29 '19 at 07:43
  • what you addressed are just typos, thanks. But the problem is not solved not even addressed – Allaw Hussein Dec 29 '19 at 12:25