본문 바로가기

ECIM list (Help!)

배열을 활용한 2의 100승 구하기 Calculate using array. (2 power 100, 2^100)

 int 형을 이용해서는 2의 31승 까지만 표현할 수 있습니다. Char 배열을 이용해서 이보다 더 큰 수를 계산해 봅시다. 예제는 2의 100승 입니다.

/* Written by rinehart@naver.com      */
/* 2009. 2. 9.                                   */
/* Tested on Windows, Cygwin, gcc  */

#include <stdio.h>

#define MAX (100)
#define TRUE    1
#define FALSE   0

int main()
{
    char    a_Result[MAX];
    int v_input = 0;
    int i = 0, j= 0; //Loop
    int b_first_non_zero = FALSE;   //To avoid straight Zero print out.

    memset (a_Result, 0x00, MAX);

    printf ("Input Power number : " );    // Get an input number
    scanf ("%d", &v_input);

    if (v_input > MAX || v_input < 0)    // input check
    {
        printf ("Wrong number\n");
        return 0;   //Quit program.
    }

    if (v_input >= 0)
    {
        a_Result[0] = 1;    // 2 power 0 is always 1. And Initialze a_Result.
    }

    //Calculation loop
    for (i = 0; i < v_input; i++)  
    {
        int v_temp = 0;
        int v_carry_before = 0;
        int v_carry_over = 0;

        for (j = 0; j < MAX-1; j++) //MAX -1 : to avoid overflow.
        {
            v_temp = a_Result[j];  
            v_temp = v_temp * 2;    // x2 to each digit.
            v_carry_before = v_carry_over;
            v_carry_over = 0;

            if (v_temp > 9)
            {
                v_carry_over = 1;
                v_temp -= 10;
            }

            a_Result[j] = v_temp +v_carry_before ;
            v_carry_before = 0;
        }
    }

    printf ("The Result of 2 power v_input is \n");    // Result print routine.

    for (i = MAX-1; i >= 0; i--)
    {
        if (a_Result[i] != 0)
        {
            b_first_non_zero = TRUE;
            printf("%d", a_Result[i]);
        }
        else if ((a_Result[i] == 0) && (b_first_non_zero == TRUE))
        {
            printf("%d", a_Result[i]);
        }
    }
   
    printf (".\n");

    return 0;
}