Why this code is wrong[small factorial]

Capture

You have decremented K in while loop itself so -
error 1: You have used postdecrement counter K-- ,so in loop when your K reaches 1 , k>0
would be true but due to post decrement K-- it would become 0 in loop. So your ans
would always be 0
error 2: It would be decremented to 4 so your first ans would be
ans = ans*4 , which is wrong as it should start from 5.
So due to this we cannot use predecrement counter --k

Solution:
while(k>0)
{
ans = ans*k;
k–; // --k can also be used
}

it is still saying wrong answer even after correcting the code.
#include
using namespace std;

int main() {
// your code goes here
int t;
cin>>t;
while(t–){
int n,ans=1;
cin>>n;
int k=n;
if(n==0){
ans=1;
}
while(k>0)
{
ans = ans*n;
–n;
–k;

   }
    cout<<ans<<"\n";
}
return 0;

}

Firstly, please use preformatted text. Just ``` before and after your code. Example:

//This is just an example
#include <iostream> 
using namespace std;

int main() {
    cout << "I am using preformatted text" << endl;
}

Secondly, the value that you are storing in the variable ans is overflowing. You can check it if you input the value of n as 20. You will need to use string manipulation on this, check online sources, they are very helpful.

1 Like

in int you can store maximum 12!
so if n is greater than n,then it won,t work.
for upto 20! you can use long long int.
above that you have to use string then.

As @aryan12 mentioned, please preformat your code! This will help us more to debug your code, which in turn, will help you get your answer.

Now for your code,

It works perfectly, but only for really small numbers!

I would recommend you to use long long int to store the factorial as you can store larger numbers, but this entirely depends on the constraints.

Also, here would be a much better code for computing the factorial:

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

#define int long long

signed main()
{
    int t; cin >> t;

    while(t--){
        int n; cin >> n;

        int fact = 1;

        for(int i = 1; i <= n; i++)
            fact *= i;

        cout << fact << "\n";
    }
}

i think this is correct actually
while(k>0)
{
ans = ans*k;
k–; // --k can also be used
}

still it says wrong. I don’t understand why

Do you know 100! \approx 10^{157}? That won’t fit in even an unsigned long long.

1 Like

You will need string manipulation for this problem. Check out online sources, they are quite good.

1 Like

Can you please provide the problem link?

Btw, I just realized even multiplication in a vector, (not a string) can work.