0
0

C言語でpow関数を実装してみた。

Last updated at Posted at 2023-09-17

注意!

・以下のネタバレあり。

pow関数とは

・今回、実装するpow関数については以下の記事にまとめています。

ACしたコード && 解説

#include <stdio.h>
int main(void){
    //標準入力からaを受け取るのでint型でaを宣言する。
    int a;
    //標準入力からaを受け取るのでint型でbを宣言する。
    int b;
    //標準入力からaとbを受け取るので標準入力から値を受け取る。
    scanf("%d%d",&a,&b);
    // printf("%d%d",a,b);

    //累乗は掛け算をしていくので初期値は1にする。
    //初期値を0にすると0に掛け算をすることになるのでどんなに掛け算しても結果が0になる。
    int sumA = 1;
    //aをb回掛け算することで冪乗の掛け算ができる。
    for(int i = 0; i < b; i++){
        sumA *= a;
    }
    // printf("%d",sumA);

    //bをa回掛け算することで冪乗の掛け算ができる。
    int sumB = 1;
    for(int i = 0; i < a; i++){
        sumB *= b;
    }
    // printf("%d",sumB);
    //それぞれの結果を足し算する。
    printf("%d\n",sumA + sumB);
    return(0);
}

入力例
2 8
出力例
320

ACしたコードを良いコードにしてみる①

・pow関数を使って解いてみる。

#include<stdio.h>
//pow関数を使うために必要
#include<math.h>
int main()
{
  int a;
  int b;
  scanf("%d%d",&a,&b);
  
  int powA;
  int powB;
  int ans = 0;
  
  powA = pow(a,b);
  powB = pow(b,a);
  ans = powA + powB;
  printf("%d",ans);
  
  return(0);
}

入力例
2 8
出力例
320

ACしたコードを良いコードにしてみる②

・pow関数を使ってコードを短くしてみた。

#include <stdio.h>
#include <math.h>

int main(void){
   
   int a;
   int b;
   scanf("%d%d",&a,&b);
   
   int ans = 0;
   ans = pow(a,b) + pow(b,a);
   printf("%d",ans);
   
   return 0; 
}

入力例
2 8
出力例
320

ACしたコードを良いコードにしてみる③

・教えて頂いたニ乗法を使って解いてみる。

#include <stdio.h>

int main() {
    int a, b;
    scanf("%d %d", &a, &b);

    int result = 1;
    int baseA = a;
    int baseB = b;

    while (b > 0) {
        if (b % 2 == 1) {
            result *= baseA;
        }
        baseA *= baseA;
        b /= 2;
    }

    int  tempResult = 1;
    while (a > 0) {
        if (a % 2 == 1) {
            tempResult *= baseB;
        }
        baseB *= baseB;
        a /= 2;
    }

    result += tempResult;

    printf("%d\n", result);

    return 0;
}

0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0