Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiplication and Division unsigned integers

In my program , I have to perform arithmetic operations on unsigned integers.

  • The variable a has a range from 0 to 4294967295.
  • The variable b has a range from 0 to 32.

When I check the boundary condition by taking the maximun values for a and b,I am getting 0 as the answer since overflow occurs when I try to multiply a and MAX_NS.Ideally I should get 7 as the answer.How could I write the program such that overflow is taken care of and I get 7 as the answer and hopefully it works for other valid value range for a and b.Thanks.

#include "stdio.h"

#define MAX_NS 1000000000

 int main()
 {
    unsigned int a =  4294967295;
    unsigned int b =  32 ;

    unsigned int c = ((b * MAX_NS)/a);
    printf("%d",c);


 }

**Edit:**Please note that I can't use unsigned long long.I can use only unsigned int for the variables.

like image 533
Gopala Krishna Avatar asked Oct 30 '22 00:10

Gopala Krishna


1 Answers

Here is solution as Weather Vane suggested

#include "stdio.h"

#define MAX_NS 1000000000

int main()
{
    unsigned long long a = 4294967295;
    unsigned long long b = 32;

    unsigned long long c = ((b * MAX_NS) / a);
    printf("%llu", c);
}
like image 107
vlada Avatar answered Nov 15 '22 12:11

vlada