0

I have typed out a simple program counting the number of positive divisors of a number in C, which works in CodeBlocks GCC compiler but not in the online compiler provided by the school, where it prints out some numbers close to 22k (22019 21873) etc after some inputs.

For example, for input 10 the program prints out 4 which the number of divisors, but in the online compiler it prints out 22019. I noticed when i changed the order of some conditions in the if statements from if (n<0) to if (0>n) the numbers also changed (the 22019 became 22xxx) to numbers different from the first time. Here's the code:

#include <stdio.h>
#include <stdlib.h>

int main()
{
  int c, n, res = 0;
  int i = 1;

  scanf("%d", &n);
  if (0>n)
    printf("Wrong Input");
  else {
    while (n>=i)
      {
        res = n%i;
        if (res == 0) {
          c++;
          i++;
        }
        else {
          i++;
        }
      }
    printf("%d", c);
  }
  return 0;
}
alinsoar
  • 15,386
  • 4
  • 57
  • 74
  • 5
    What is the initial value of `c`? If you answer `0` then you need to study more. – Some programmer dude Jan 09 '23 at 10:44
  • 2
    `int c, n, res = 0;` only initializes `res`. – Ian Abbott Jan 09 '23 at 10:50
  • See the linked duplicates. As for when a program starts behaving differently on different compilers, that's a strong indication that is contains some form of "poorly defined behavior" - in this case undefined behavior. – Lundin Jan 09 '23 at 10:52
  • 1
    Thanks for the quick response everyone, turns out it wasn't the compilers fault, but my inexperience with C that had me thinking I could assign value to all integers in the way i typed the first line in main. – Petra Kotrona Jan 09 '23 at 11:23
  • @PetraKotrona Also `while (n>=i) { ... }` is very inefficient. Better as `while (i <= n/i) { res = n%i; if (res == 0) { cnt += 1 + (i < n/i); } i++}`. – chux - Reinstate Monica Jan 09 '23 at 16:13

0 Answers0