abhishekagrawal 0 Newbie Poster

Dear All,

I have written a program to find the smallest divisor of an input number. The code gives me an error in lines 19 and 23. The error is invalid operands to binary %. Please help me to troubleshoot, thank you. Below is my code:

#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int main()
{
int n,r,sdivisor;
double d,sqroot,comp;
printf("Enter the number whose smallest divisor has to be found");
scanf("%d",&n);
if(n%2==0)
{
          printf("the smallest divisor is 2");
}
else 
{
 sqroot=sqrt(n);
 d=3;
}
comp=n%d;
while(comp!=0 & d<sqroot)
{
 d=d+2;
 comp=n%d;
}
if(comp==0)
{
 sdivisor=d;
}
else
{
 sdivisor=1;
}
system("pause");
return 0;
}

Thank you for your reply.

Dani AI

Generated

For : the compile errors on the lines that use n % d come from using the modulus operator with floating‑point operands. In C the % operator only works on integer types; declaring d and comp as double makes n % d invalid. The loop condition also uses a single & (bitwise) instead of the logical &&, and treating a prime’s smallest divisor as 1 is incorrect — it should be the number itself (for n > 1).

Minimal, focused fixes (replace the problematic declarations/loop):

/* use integers for modulus */
int d = 3;
int limit = (int)sqrt((double)n);

/* test n % d directly, and use logical AND */
while (d <= limit && n % d != 0) {
    d += 2;
}

/* if no odd divisor found, n is prime */
sdivisor = (n % d == 0) ? d : n;

Notes and quick improvements:

  • Remove the separate comp double — test n % d directly as an int.
  • Use d <= limit (limit = (int)sqrt((double)n)) to avoid skipping edge cases; or avoid sqrt() entirely and use d*(long long)d <= n to prevent floating precision/overflow issues for large n.
  • Handle n <= 1 and negative inputs explicitly. For large inputs, switch int to long long and use proper scanf/printf formats.
  • Replace system("pause") with portable code (or omit) and compile with -Wall -Wextra to catch similar mistakes early.

Quick test cases (expected outputs): n=1 -> 1, n=2 -> 2, n=15 -> 3, n=17 -> 17.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.