WA in RESQ

I used the following code tried many test cases but when I submit I get wrong answer in the problem Arranging Cup Cakes( http://www.codechef.com/problems/RESQ )
Here’s the code I used

#include
#include<math.h>
long divsum(long n);
int main()
{
int cases,x=0;
long num;
scanf("%ld",&cases);
for(int j=0;j<cases;j++)
{
scanf("%ld",&num);
if(num==1)
{
printf("%d\n",x);
}
else
{
printf("%lld\n",divsum(num));
}
}
}
long divsum(long n)
{
long k;
long diff=10000000,tmp;
k=(long)sqrt((float)n);
if(k*k==n)
{
diff=0;
}
if(n%2!=0)
{
for(long i=1;i<=k;i+=2)
{
if(n%i==0)
{
tmp=(long)fabs((float)n/i-(float)i);
if(tmp<diff)
{
diff=tmp;
}
}
}
}
else
{
for(int i=1;i<=k;i++)
{
if(n%i==0)
{
tmp=(long)fabs((float)i-(float)n/i);
if(diff>tmp)
{
diff=tmp;
}
}
}
}
return diff;
}