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

int main() {
    int n, i;

    printf("n: ");
    scanf("%d", &n);

    for (i = 100; i <= 999; i++) {
        int x = i / 100;
        int y = i / 10 % 10;
        int z = i % 10;
        
        int suma = x * x + y * y - z * z;

        if (n % suma == 0)
            printf("%d %d %d %d\n", i, x, y, z);
    }

    return 0;
}

This code is supposed to check if a 3 digit number(xyz) follows this property:

n % (x2 + y2 - z2) == 0.

For some reason, when I run this code, it just crashes, without any errors or warnings. I'm new to programming, and I would like some help.

I tried changing the if statement, but it doesn't change anything. What am I missing?

chqrlie
  • 131,814
  • 10
  • 121
  • 189
  • 1
    [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) – Jesper Juhl Nov 27 '22 at 16:01
  • Welcome to Stack Overflow. Please read the [About] and [Ask] pages. Do not use both the C and C++ tags on a question unless it is about how the two languages interwork. Your code is C, you say: use just the C tag. Not doing that is likely to earn you downvotes. – Jonathan Leffler Nov 27 '22 at 16:03
  • When `x = 3`, `y = 4`, `z = 5`, you'll have `suma = 0` and `n % suma` will trigger a 'floating point exception' (FPE) because you're dividing by zero. Once upon a long time ago, FPEs were generated for floating-point arithmetic too; the name hasn't been changed even though integer division by zero is just about the only cause of them these days. Granted, your numbers are constrained to 100..999, so the values might be 120, 160, 200 instead — that's a 3:4:5 right-triangle too. – Jonathan Leffler Nov 27 '22 at 16:05

1 Answers1

3

Your code has a divide by zero, which is a problem in C. To avoid it, first check if suma is non-zero:

if (suma && n % suma == 0)
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
lorro
  • 10,687
  • 23
  • 36