multiplying complex numbers in C

129 Views Asked by At

My code seems working but the online judge doesn't accept it. Here's the instruction:

Problem Statement Write a C Program that will compute for the product of two complex numbers.

Input

Input starts with a number N and is followed by N pairs of complex numbers of the form a + bi, c + di

Output

The product of the two complex numbers.

Limits

1<=N<=20

The parts of the complex numbers are integers.

Notes

Problems will have test cases that are not listed in their specification. Your solution must produce the right output for these hidden test cases.

Sample Input #1

3
1 + 2i, 3 - 4i
3 - 2i, 2 + 3i
9 - 2i, 3 - 2i

Sample Output #1

11 + 2i
12 + 5i
23 - 24i

Here's my code

#include <stdio.h>

int main(void) {
    int n;
    scanf("%d", &n);

    for (int i = 0; i < n; i++) {
        int a, b, c, d;
        char sign1, sign2;
      
        scanf("%d %c %di, %d %c %di", &a, &sign1, &b, &c, &sign2, &d);

        if (sign1 == '-')
            b = -b;
        if (sign2 == '-')
            d = -d;

        int real = (a * c) - (b * d);
        int im = (b * c) + (a * d);

        if (im < 0) {
          if(real != 0){
            printf("%d %c %di\n", real, '-', -im); }
          else {
            printf("%c %di\n", '-', -im);
        } }

        else if (im > 0){
          if(real != 0){
            printf("%d %c %di\n", real, '+', im); }
          else {
            printf("%di\n", im);
          }}

        else if (im == 0){
          if(real != 0){
            printf("%d\n", real);
          }
          else{
            printf("0\n");
          }
        }
      }
    
  
    return 0;
}

ps. sorry my code's messy. i have just started learning

1

There are 1 best solutions below

2
chux - Reinstate Monica On

Suggested changes:

  • Use wider math to prevent overflow.
    // int real = (a * c) - (b * d);
    long long real = (1LL* a * c) - (1LL* b * d);

Same for im and adjust print specifiers.

  • Asymmetric output

Below 2 are not symmetric. Perhaps negative imaginary values, when alone are printed without a subtraction sign.

    printf("%c %di\n", '-', -im);
    ... 
    printf("%di\n", im);

Suggest:

    printf("%di\n", im);
    ... 
    printf("%di\n", im);

... or maybe with a zero real part as in 0 - 2i, 0 + 2i.

or simply:

        long long real = (1LL * a * c) - (1LL * b * d);
        long long im = (1LL * b * c) + (1LL * a * d);
        printf("%lld %c %lldi\n", real, (im < 0 ? '-' : '+'), llabs(im));
         
  • Check return value of scanf().