-4
#include <stdio.h>
int test1(int x, int n){
    int times=31/n;
    return ((1-(1<<(n*times)))/(1-(1<<n)));
}

I am doing a calculation where 1<=n<=32

It only works when 1<=n<=31, how can I change it for n=32? As I test its n=32 case in xcode, it triggers the debugger and shows thread 1 exc_arithmetic(code=exc_i386_div....
Thank you in advance.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Jack
  • 1
  • 2

3 Answers3

1

There is a decent chance that when you do 1 << 32, it is treated as 1 << 0 (and, since you're invoking undefined behaviour, that's OK), and you then get the 'floating point exception' because you are doing an integer 'divide by zero'. These days, that's the most common cause for the exception. If you were doing floating-point arithmetic, you'd get an infinity returned (silently) for division by zero.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
0

I just found out how I can fix this. the problem is 1<<32 case (which I will try to avoid).

I changed 1 << n to (1 << (n-1) )*2, another way to apply the math.

return ((1-(1<<(n*times)))/(1- (1<<(n-1))*2  ));
David C. Rankin
  • 81,885
  • 6
  • 58
  • 85
Jack
  • 1
  • 2
  • If your `int` type is a 32-bit type, you are still invoking undefined behaviour. And if it was longer than 32 bits, you wouldn't have been getting an error in the first place. Can you explain what your calculation is supposed to evaluate? – Jonathan Leffler Oct 08 '16 at 00:29
  • @JonathanLeffler, what I was doing is geting a 32-bit int and number n as inputs, and the output should be filled up with repeating n bits of the input. For example, if the input is 1, and 2. (the repeating pattern is 01), the output should be 0x55555555. if input is 0x12345678, 32, the output will just be 0x12345678. I get the output by finding out that I can calculate the sum of sequential series. and the one I am asking is part of it. – Jack Oct 09 '16 at 04:20
0

Some modern implementations for 2's-complement platforms generate a "floating point exception" in response to integer division overflow that occurs in the following code

int a = INT_MIN;
int b = -1;
int c = a / b;

even thought there's nothing "floating" there. GCC is one example of such platform.

Apparently, your expression runs into the same kind of problem as a practical platform-specific manifestation of undefined behavior triggered by "overshifting" an integer.

P.S. As noted by @Jonathan Leffler, integer division by zero also generates a "floating point exception" in GCC, which is probably even more likely to occur in your case.

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765