Here’s my code :
#include <stdio.h>
int main (void) {
unsigned long long t, y, z, a;
a = 0;
scanf ("%I64u %I64u", &t, &y);
for (t; t > 0 ; --t) {
scanf ("%i", &z);
if (t == 0)
break;
else if (z % y == 0)
++a;
}
printf ("%i\n", a);
return 0;
}
I am a beginner and I haven’t learnt about arrays, functions or an other advanced topics. Is it possible to optimize this solution without using any advanced features of C. I know about looping using for
, while
and do
statements and decision making with if
and else if
. The above code exceeds the time limit.
this is your corrected code…
#include <stdio.h>
int main (void) {
int t, y, z, a;
a = 0;
scanf ("%d%d",&t,&y);
while(t--)
{
scanf ("%d",&z);
if (z % y == 0)
++a;
}
printf ("%d\n", a);
return 0;
}
explanation for the 6th line:-
while(t--)
all numbers(positive & negative) except zero are considered as TRUE…so when t will become ‘0’ the loop will end…example:-
let t=5;
1st time t value will be 5 that is considered as TRUE…then it is decremented to 4 as “–” is post decrement operator…!!!
2nd time t will be 4 that will be considered as true…then it is decremented to 3!!!
3rd time t will be 3 that will be considered as true…then it is decremented to 2!!!
4nd time t will be 2 that will be considered as true…then it is decremented to 1!!!
5th time t will be 1 that will be considered as true…then it is decremented to 0!!!
6th time as t is 0…it will be considered as false and the loop will terminate!!!
hence the total number of iterations will be 5!!!
1 Like
I modified my code after seeing yours and it got accepted as the correct answer! I just changed unsigned long long int to int and changed the format specifier accordingly. But I don’t understand why this was causing the exceeding time limit.
Also, I did not understand the 6th line of your code. The format of while statement is ‘while (loop_condition)’, so the loop condition in your code which will be evaluated is (–t). But --t looks like a looping expression. How is it be evaluated?