Thread: Raising an Integer to a power

  1. #1
    Registered User
    Join Date
    Sep 2012
    Posts
    14

    Raising an Integer to a power

    Hello, I'm currently writing a program that is supposed to raise an integer to a power. However, the output keeps printing as going to infinity rather than the actual number when using the test results. I tried changing the double type to a long double, but it still is not large enough. Earlier when I was working on the program though, it did not seem to have this problem.


    Any help at all would be greatly appreciated.

    Thank you.

    EDIT: The iterative function on the bottom does not work. I have not been able to finish it due to trying to stop the result from printing as 1.#NF00.

    Code:
    #include "stdafx.h"//standard library inclusion
    #include "stdio.h"
    #include "conio.h"
    #include "time.h"
    
    clock_t start,stop;//built in type for processor time (ticks)
    double duration;//Records the run time, in seconds, of a function 
    
    long double Recur(double base, int pow);//Declaration of function for recursion.
    long double Expon(double base, int pow);//Declaration of function for N-1 loop.
    long double Iter(double base, int pow);//Declaration of function using iteration.
    
    int  main(void)
    {
        //This program raises a given integer (base) to a power (pow)
    
        int  pow=0, algo, test=0;//algo will be used to initiate the chosen algorithm. Test for choosing whether or not to run the test cases.
        double base;
        long double result;//Stored as a long double as in the test files the number is very large
    
        printf("If you want to run Algorithm 1: Enter 1\nIf you want to run Algorithm 2(recursive): Enter 2\nIf you want to run Algorithm 3(iterative): Enter 3\n");
        scanf("%d", &algo);//Choose which algorithm to run.
    
        printf("If you want to run the test cases: Enter 1: ");
        scanf("%d", &test);//Choose whether or not to run the test cases.
        
        if(test!=1){//If Not running test cases, user inputs own base and power.
            printf("Please enter your base: ");
            scanf("%lf", &base);
            printf("Please enter your power: ");
            scanf("%d",&pow);//take in input for functions.
    
            if(algo=1){//Will run algorithm one and clock time
                start=clock();
                result=Expon(base,pow);
                stop=clock();
            }
            else if(algo=2){//Will run algorithm two and clock time
                start=clock();
                result=Recur(base,pow);
                stop=clock();
            }
            else{//Will run algorithm three and clock time
                start=clock();
                result=Iter(base,pow);
                stop=clock();
            }
    
            printf("%llf to the power of %d = %llf.\n",base, pow, result);//Print out results of chosen algorithm
    
            duration = ((double)(stop - start))/CLK_TCK;  //Print out duration of algorithm time
            printf("Duration = %llf",duration);
    
        }
    
    
        else{//Run Test cases
            base=1.0001;
            int arraypow[8]= {1000,5000,10000, 20000, 40000, 60000, 80000, 100000};//Go through the array of powers in the test cases
            int i=0;
    
            for(i=0;i<8;i++){//Use loop to go through the test cases
                if(algo=1){//Test cases for algorithm 1
                    pow=arraypow[i];
                    start=clock();
                    result=Expon(base,pow);//Function call for algorithm 1
                    stop=clock();
                    printf("%lf to the power of %d = %Lf.\n",base, pow, result);//Print out results as each power is used.
    
                    duration = ((double)(stop - start))/CLK_TCK;   //Calculate duration of algorithm
                    printf("Duration = %lf\n",duration);
                }
                else if(algo=2){//Test cases for algorithm 2 (recursive)
                    pow=arraypow[i];
                    start=clock();
                    result=Recur(base,pow);//Function call for algorithm 2 Recursive
                    stop=clock();
                    printf("%lf to the power of %d = %Lf.\n",base, pow, result);//Print out results as each power is used.
    
                    duration = ((double)(stop - start))/CLK_TCK;  //Calculate duration of algorithm
                    printf("Duration = %lf",duration);
                }
                else{//Test cases for algorithm 2 (iteration)
                    pow=arraypow[i];
                    start=clock();
                    result=Iter(base,pow);//Function call for algorithm 2 Iterartive
                    stop=clock();
                    printf("%lf to the power of %d = %Lf.\n",base, pow, result);//Print out results as each power is used.
    
                    duration = ((double)(stop - start))/CLK_TCK;  //Calculate duration of algorithm
                    printf("Duration = %lf",duration);
                }
            }
        }
    
        getch();//Stop prgram from exiting after executing
        getch();
        return 0;
    }
    
    
    long double Expon(double base, int pow)//Function for algorithm 1
    {
        double result;
        if(pow==0)
            result = 1;
        else if(pow==1)
            result = base;
        for(pow;pow>2;pow--){//Loop for N-1 
            base=base*base;
            result=base;//Update result as power increases
        }
    
        return result;
    }
    
    
    long double Recur(double base, int pow)//Function for algorithm 2 (Recursive)
    {
        double result;
        if(pow==0)
            return result = 1;//Case for when power is equal to 0.
        else if(pow==1)
            return result = base;//Case for when power is equal to 1
        else if(pow%2==0){
            return Recur(base*base,pow/2);//Case for if pow is even
        }
        else
            return Recur(base*base,pow/2)*base;//Case for if pow is odd
    }
    
    long double Iter(double base, int pow)//Function for algorithm 2 (Iterative)
    {
        double result;
    
        while(pow>1){
    
            if (pow%2==0){
                base=(base*base);
                pow=pow/2;
                result=base;
            }
            else{
                base=base*base;
                pow= pow/2 +1;
                result=base;
            }
        }
        return result;
    }
    Last edited by aileentas; 09-18-2012 at 09:55 PM.

  2. #2
    TEIAM - problem solved
    Join Date
    Apr 2012
    Location
    Melbourne Australia
    Posts
    1,907
    Typo in expon()
    Code:
    base=base base*;
    Last edited by Click_here; 09-18-2012 at 09:57 PM. Reason: typed 'on' instead of 'in'
    Fact - Beethoven wrote his first symphony in C

  3. #3
    Registered User
    Join Date
    Sep 2012
    Posts
    14
    Ah, thank you, I changed that in my code, but forgot to change what I posted here as well. The 1.#NF00 error is still a problem though.

  4. #4
    TEIAM - problem solved
    Join Date
    Apr 2012
    Location
    Melbourne Australia
    Posts
    1,907
    What is the function supposed to do?
    Last edited by Click_here; 09-18-2012 at 10:04 PM. Reason: re-read problem
    Fact - Beethoven wrote his first symphony in C

  5. #5
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Quote Originally Posted by aileentas View Post
    Ah, thank you, I changed that in my code, but forgot to change what I posted here as well. The 1.#NF00 error is still a problem though.
    For C, you should be using include of "stdio.h", instead of stdafx.h. Check if your program has a dot c extension, also. An extension of dot cpp would also indicate that your program is being saved as a c++ program.

    Anyway. For your data type, I suggest using long long int's, or even unsigned long long int's - that should give you plenty of range, and stop the problems of double % int == 0, kind of code.

    Doubles are floats and all floats involve CLOSE approximations of numbers, BUT NOT QUITE. So they won't match up with int's, on many cases.

    Give that a try.

  6. #6
    TEIAM - problem solved
    Join Date
    Apr 2012
    Location
    Melbourne Australia
    Posts
    1,907
    Code:
    if(algo=1)
    Should this be

    Code:
    if(algo==1)
    Fact - Beethoven wrote his first symphony in C

  7. #7
    Registered User
    Join Date
    Sep 2012
    Posts
    14
    The function is supposed to raise a an integer ( or a decimal) (base )to a power (pow) using recursion, iteration, and N-1.


    I have included stdio.h in the function, but if I don't include stdafx.h as well, it won't run. I tried saving the program as a .c instead as well, but when I did that it said that my array had terms with too many characters and wouldn't run.

    And, thank you for the data type advice. I will try it out and see how it works.


    Oh, I can't believe I missed that I didn't use two '='. I'll fix that now.

    EDIT:And, now my recursive function works. Thank you so much.
    Last edited by aileentas; 09-18-2012 at 10:14 PM.

  8. #8
    - - - - - - - - oogabooga's Avatar
    Join Date
    Jan 2008
    Posts
    2,808
    Quote Originally Posted by Adak View Post
    you should be using include of "stdio.h", instead of stdafx.h.
    I think you were confused by his inaccurate comment. stdafx.h has nothing to do with "standard library inclusion". It's related to pre-compiled headers in MSVC.

    Doubles are floats and all floats involve CLOSE approximations of numbers, BUT NOT QUITE. So they won't match up with int's, on many cases.
    Actually, doubles will represent ints perfectly unless the magnitude is too great.
    The cost of software maintenance increases with the square of the programmer's creativity. - Robert D. Bliss

  9. #9
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Quote Originally Posted by aileentas View Post
    The function is supposed to raise a an integer ( or a decimal) (base )to a power (pow) using recursion, iteration, and N-1.


    I have included stdio.h in the function, but if I don't include stdafx.h as well, it won't run. I tried saving the program as a .c instead as well, but when I did that it said that my array had terms with too many characters and wouldn't run.

    And, thank you for the data type advice. I will try it out and see how it works.


    Oh, I can't believe I missed that I didn't use two '='. I'll fix that now.
    It won't run without stdafx.h, because you're compiler is C++, instead of C. Set your options so dot c extension programs, are to be compiled with the C compiler, only, and dot cpp are to be compiled with the cpp compiler. They are NOT the same language, and WILL cause problems.

    We can fix your C problems, just post the code. Your arraypow[] is correctly sized, imo.

  10. #10
    TEIAM - problem solved
    Join Date
    Apr 2012
    Location
    Melbourne Australia
    Posts
    1,907
    now my recursive function works. Thank you so much
    That's great to hear.

    What appears to have been happening is that the =/== mistake was forcing your code to do the expon() function every time - With that typo in it, it would not work the way you wanted to.
    Fact - Beethoven wrote his first symphony in C

  11. #11
    Registered User
    Join Date
    Sep 2012
    Posts
    14
    Yes, It seems to be working properly now and I can focus on finishing it.
    Last edited by aileentas; 09-18-2012 at 10:44 PM.

  12. #12
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Go into your compiler options, and see how it's set up. Default on mine was dot c programs were compiled with C compiler, and dot cpp programs got the cpp compiler.

    Then set your project options. You may need to rebuild the project, not just recompile it. (You have a button for it).

    If you want to keep using C++, I have no gripes about it, but it's an error to mix up C advice with C++ code, and it will bite/confuse us, once in awhile.

  13. #13
    Registered User
    Join Date
    Sep 2012
    Posts
    14
    Okay, I've found how to make it a C program properly now. Thank you, I'll make sure I don't get the mixed up again.

  14. #14
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    This should give you an error, if you do it:

    Code:
    doubeVariable % integerVariable
    I get:

    error #2168: Operands of '%' have incompatible types 'double' and 'int'.

  15. #15
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    It might be running successfully now, but the result will be horribly wrong.
    You have gotten the implementation of Expon wrong, and are actually calculating "base to the power of (base to the power of pow)" i.e. base^(base^pow) where ^ means "to the power of".
    Or as an example, 2 to the power of 8 should be 256, but instead you'd get a result that is 77 decimal digits long!

    First work out which algorithm you are intending to use. The slow one where you multiply the answer by base each time, or the binary exponentation method where you multiply either by base or by a binary power of base.

    This is why you need to test your code with inputs and corresponding expected outputs, in order to test if it is working correctly.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Raising to a power
    By teelnaw in forum C Programming
    Replies: 6
    Last Post: 11-07-2010, 01:35 AM
  2. Help with checking, raising to the power of 2
    By philippe in forum C++ Programming
    Replies: 5
    Last Post: 11-14-2005, 07:30 PM
  3. Replies: 6
    Last Post: 11-08-2005, 03:05 PM
  4. raising to a power
    By next_to_nothing in forum C++ Programming
    Replies: 5
    Last Post: 10-22-2002, 04:00 AM
  5. Raising to a power
    By Nate2430 in forum C++ Programming
    Replies: 1
    Last Post: 09-15-2001, 04:44 PM