Thread: exponents

  1. #1
    Registered User
    Join Date
    Aug 2004
    Posts
    5

    exponents

    I am kinda new to C and was wondering how would i do
    2 to the power of n and then subtract one.

    thank you

  2. #2
    ... kermit's Avatar
    Join Date
    Jan 2003
    Posts
    1,534
    you could use the pow() function:

    it would look something like this
    Code:
    pow(base, n); /* in your case pow is the function call, base would be 2
                     and n is whatever number you want to raise it to */
    When you have that number, it is relatively easy to subtract 1 from it.

    to use pow() make sure you #include math.h, and if you are using gcc, be sure to the -lm flag to link the math library.

    pow returns a double, so be sure to keep that in mind when you use it.

    ~/
    Last edited by kermit; 08-14-2004 at 02:19 PM.

  3. #3
    Registered User
    Join Date
    Jun 2004
    Posts
    84
    pow is unnesseserry here, he only wants power of 2. If n is less than 31 then:
    Code:
    unsigned int answer, n = SOMETHING;
    
    answer = ~(0xFFFFFFFF<<n);

  4. #4
    & the hat of GPL slaying Thantos's Avatar
    Join Date
    Sep 2001
    Posts
    5,681
    Bitwise operations should not be used in place of pow(). What happens if the integer is a negative, is a 64 bit number, is a 128 bit number. What if they want to use 3 instead of 2, or negitive 2, or a negative power.

    Use pow() and save yourself a lot of trouble.

  5. #5
    Registered User
    Join Date
    Apr 2002
    Posts
    1,571
    Also important, what if they want to raise a real value to an exponent. Shifting certainly won't work.

    edit: I know he said 2 raised to n , but still thought it should be mentioned.
    "...the results are undefined, and we all know what "undefined" means: it means it works during development, it works during testing, and it blows up in your most important customers' faces." --Scott Meyers

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. exponents are LAAAME
    By Sm33zy in forum C Programming
    Replies: 8
    Last Post: 11-21-2008, 10:10 PM
  2. Fraction Exponents
    By ninjaturtle[k9] in forum C++ Programming
    Replies: 4
    Last Post: 10-18-2004, 10:46 AM
  3. God, i feel like a n00b again. How do i do exponents?
    By Inquirer in forum C++ Programming
    Replies: 13
    Last Post: 09-01-2003, 08:41 PM
  4. how to use exponents
    By guitargatler in forum C++ Programming
    Replies: 11
    Last Post: 02-01-2003, 09:09 PM
  5. For loop and exponents
    By TrazPFloyd in forum C++ Programming
    Replies: 5
    Last Post: 10-15-2002, 05:19 AM