Problem Link: CodeChef: Practical coding for everyone
Learning course: Learn C++
My code
#include <bits/stdc++.h>
using namespace std;
int main() {
int num;
int fact = 1;
cin >> num;
for(int a = num; a >= 2; a = a--)
{
fact = fact * a;
}
cout << "The factorial of the given number is: " << fact << endl;
return 0;
}
My issue
why time limit excedded in this way and not in (–a) in the for loop i think the are same in this condition’
#include<bits/stdc++.h>
using namespace std;
int main(){
int num;
cin>>num;
int x=1;
int y=1;
while(x<=num){
y*=x;
x++;
}
cout<<"The factorial of "<<num<<" is :"<<y;
return 0;
}
When you do a = a--
, what happens is that a
is decremented by 1, but the previous value is still assigned to the new variable. So in effect the value of a
is never changing in this loop.
For a = --a
, here also the value is decremented by 1 and the new value is assigned to a
. Thus a
keeps decreasing.
An easy way to understand this is by using two different variables. Run these two codes by yourself to see.
int a = 2;
int b = a--;
cout<<b<<'\n'; // b will be 2
int a = 2;
int b = --a;
cout<<b<<'\n'; // b will be 1