It follows an alternative as short as Thiago’s answer, but it works with numbers that are not multiples of 4:
int main(){
unsigned short int in, i;
scanf("%hd", &in);
for( i = 1; i <= in; i++ ) printf( i & 3 ? "%d " : "PUM\n", i );
return 0;
}
See working with number 10 as an example on IDEONE.
The operation i & 3
is a quick way to get the least significant 2 bits of the counter, effectively returning 0
for all cases where the "PMU" message should be displayed.
The ternary operator will use "%d "
in all cases where the mentioned expression does not return 0
I showed the ternary as an alternative to if
, but it is worth saying that normally, if the criterion is efficiency, the structure similar to @Maniero’s response is more appropriate, although longer.
Follow the code similar to @Maniero’s by swapping the rest operator for bits:
int main(){
int in, i;
scanf("%d", &in);
for ( i = 1; i <= in; i++ ) {
if (i & 3) {
printf("%d ", i);
} else {
printf("PUM\n");
}
}
return 0;
}
I put a demo on IDEONE with very little logic, but in less lines.
In case you entered with 28? You can simplify this and then you will probably be + fast.
– Maniero