# DevFred

Member

2418

840 Good

• Rank
Contributor
1. ## Different fibonacci function

Just for completeness, here is an O(n) recursive solution: int fib(int n, int a, int b) { return (n <= 0) ? a : fib(n - 1, b, a + b); } int fib(int n) { return fib(n, 0, 1); } It is possible to convert the recursive solution into an iterative one: int fib(int n) { int a = 0; int b = 1; while (n --> 0) { int s = a + b; a = b; b = s; } return a; } But I find the recursive solution aesthetically more pleasing :)
2. ## (x86) jumps in assembly

SSE has built-in instructions for determining the minimum and maximum, which allows you to get rid of jumps entirely: #include <x86intrin.h> // returns the minimum in *pa and the maximum in *pb void minmax(int* pa, int* pb, int* pc) { __m128 a = _mm_cvtsi32_ss(a, *pa); __m128 b = _mm_cvtsi32_ss(b, *pb); __m128 c = _mm_cvtsi32_ss(c, *pc); __m128 minimum = _mm_min_ss(_mm_min_ss(a, b), c); __m128 maximum = _mm_max_ss(_mm_max_ss(a, b), c); *pa = _mm_cvttss_si32(minimum); *pb = _mm_cvttss_si32(maximum); } Note that due to the conversion from int to float, only numbers up to 16777216 will be treated correctly.   If your processor supports SSE4, which is roughly six years old, you can use the full int range: void minmax(int* pa, int* pb, int* pc) { __m128i a = _mm_cvtsi32_si128(*pa); __m128i b = _mm_cvtsi32_si128(*pb); __m128i c = _mm_cvtsi32_si128(*pc); __m128i minimum = _mm_min_epi32(_mm_min_epi32(a, b), c); __m128i maximum = _mm_max_epi32(_mm_max_epi32(a, b), c); *pa = _mm_cvtsi128_si32(minimum); *pb = _mm_cvtsi128_si32(maximum); } On g++, you need to use -msse4 to enable SSE4.
3. ## calling destructor versus new object

That won't help at all, because auto mi=0; means int i=0; because 0 is of type int.

If you want to round an int down to a multiple of 64, you can use bitmasking:   x = x & ~63;   Note that this only works for powers of two.

15. ## C++'s floats not very good?

Quote:Original post by Evil Steve Write down 1 divided by 3 exactly, as a single real number. That's easy in ternary: 0.1