what's wrong with my code?

the question

#include<stdio.h>
int main()
{
int t,N,K,i;
scanf("%d",&t);
while(t–)
{
scanf("%d",&N);
scanf("%d",&K);
int P[N];
for(i=0;i<N;i++)
{
if(K>0)
{
P[i]=i+1;
K–;
}
else
P[i]=i;
printf("%d ",P[i]);
}

printf("\n");
}
return 0;

}

Blockquote

The array you print will not be a permutation if K \neq N. This is because if K < N then P[K - 1] = K = P[K + 1] and hence it is not a permutation.

The question doesn’t mention that 2 elements in the permutation cannot be same. If K<N as you said P[K-1]=K so that means Pi will be divisible by i as the question requires. And if P[K+1]=K then in that case Pi will not be divisible by i. I don’t see what’s wrong. Could you explain using an example?

Duplicates are not allowed in a permutation. Here is the definition:
A permutation is a sequence of integers from 1 to n of length n containing each number exactly once. For example, (1), (4, 3, 5, 1, 2), (3, 2, 1) are permutations, and (1, 1), (4, 3, 1), (2, 3, 4) are not.

1 Like