2

I can't figure out why it's always output nothing; can someone help me?

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

int main() {

  int i, num, sum;

  for (i = 100; i < 1000; i++)
  {
      sum = 0;
      for (num = i; num != 0; num /= 10)
      {
        sum += (i % 10) ^ 3;
      }
      if (sum == i)
        printf("%d ", i);
  }
  system("pause");
  return 0;
}
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
jsn
  • 35
  • 5

1 Answers1

3

The ^ operator is not exponentiation in C – rather, it is the bitwise XOR (exclusive OR) operator.

To raise a number to a given power, you'll need to call the pow function (but that works with floating-point numbers); alternatively, when the power is 3, just perform two consecutive multiplications.

Also, in your code, you should be using num % 10 (not i % 10) in the inner for loop:

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

int main()
{

    int i, num, sum;

    for (i = 100; i < 1000; i++) {
        sum = 0;
        for (num = i; num != 0; num /= 10) {
            int digit = num % 10;
            sum += digit * digit * digit;
        }
        if (sum == i)
            printf("%d ", i);
    }
    system("pause");
    return 0;
}
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
  • However, I'm not sure if numbers with `0` digits should count as genuine Armstrong numbers. That's something you could clarify and add to your code. – Adrian Mole Jul 10 '21 at 13:52
  • @AdrianMole They do. For instance, 407 is an Armstrong number. See [A005188 in the OEIS](https://oeis.org/A005188). Also see [Narcissistic Numbers on Wolfram](https://mathworld.wolfram.com/NarcissisticNumber.html). – Tom Karzes Jul 10 '21 at 14:55
  • @TomKarzes Thanks. Just funny that 371 is given as an example in many of the lists but 370 is seldom mentioned. – Adrian Mole Jul 10 '21 at 16:23
  • @AdrianMole I guess whenever any narcissistic number ends in `0`, you can always change the `0` to `1` to produce a new narcissistic number. – Tom Karzes Jul 10 '21 at 16:25