Recortes de codigo / Code Snippets

Saturday, May 9, 2020

Add 2 integers without using + operator

int sum(int a, int b) {
    int s = a ^ b;        // partial sum
    int c = (a & b) << 1; // carry
    
    // carry? 
    while( c != 0 ) {
        // yes -> sum it, recalc carry
        int newc = (s & c) << 1;
        s = s ^ c;
        c = newc;
    }
    
    return s;
}

Other entries:
  • isPrime: Naive version 
  • isPrime, Optimization 1: Iterate only until the square root of the number
  • isPrime, Optimization 2: Only divide by odd numbers, until the square root of the number
  • isPrime, Optimization 3: Skip the divisors that are multiple of 2 or 3
  • Keep the previosly generated primes and use them to test the following numbers.
  • isPrime, Recursive.
Posted by Rodrigo at 5:59 AM No comments:
Email ThisBlogThis!Share to XShare to FacebookShare to Pinterest
Newer Posts Older Posts Home
Subscribe to: Posts (Atom)

About Me

Rodrigo
View my complete profile

Blog Archive

  • ►  2021 (1)
    • ►  January (1)
  • ▼  2020 (4)
    • ▼  May (1)
      • Add 2 integers without using + operator
    • ►  March (2)
    • ►  February (1)
  • ►  2019 (10)
    • ►  August (4)
    • ►  July (6)
Simple theme. Powered by Blogger.
ko-fi.com/inviterodacoffee
ko-fi.com/inviterodacoffee