This code gives the smallest divisor of an integer. But the problem is I have to calculate the square root. Is there a way so that I don’t have to calculate the square root explicitly?
int d,r,n;
scanf("%d",&n);
if(n%2==0)
{
printf("2 is ans");
}
else
{
r=sqrt(n);
d=3;
while((n%d!=0)&&d<r)
{
d=d+2;
}
if(n%d==0)
printf("ans is %d",d);
else
printf("ans is 1");
}
Since
code-efficiencywas one of the tags, tweak the answers provided a bit:The compiler is more likely to reuse the result of the division operator this way.
Looking at the compiler output for
gcc -O3on the version of the loop I propose, there is only one division operation per iteration, and the result is used for both comparisons:While, the
while ((n%d) && d*d < n) d+=2;version gives:And it is clear it is doing both the multiplication and the division each iteration.