簡體   English   中英

如何使用循環查找產生自變量的基的指數

[英]How to use loops to find the exponent of a base that produces an argument

我正在嘗試使用循環來查找產生特定參數的給定基數的指數。 例如,在等式5 ^ x = 625中,5將是基數,而625將是自變量。 我知道在等式中x = 4,但是我不確定如何在回報中得到4。

這是我到目前為止的內容:

public static int log(int base, int argument) {
    int result = 1;
    for (int i=0; i<=; i++) 
    result = ;
    return result;
}

我不確定要在條件聲明和結果中加上什么。 我在這里想念什么?

編輯:我忘了提到我不使用數學庫就嘗試執行此操作。 我還認為,包括我的代碼以查找能力可能會有所幫助:

public static int pow(int base, int exponent) {
    int result = 1;
    for(int i=0; i<exponent; i++) {
        result = result*base;
    }
    return result;

我基本上只是想扭轉這一點以找到指數。

像這樣:

public static int log(int base, int argument) {
    if(argument <= 0 || base <= 0) {
        throw new IllegalArgumentException("This method only works with positive integers");
    }
    int result = 1;
    int i = 0;
    while(result < argument) {
       result = result * base;
       i++;
    }
    if(result == argument) {
       return i;
    } else {
        throw new IllegalArgumentException("There is no integer for x in base^x = argument");
    }
}

盡管可以處理所有情況,但存在一些缺陷,但這只是一個開始。

這更多是一個數學問題。

對於公式5 ^ x = 625,可以使用x =log₅(625)= log(625)/ log(5)找到x。

所以:

public static int log(int base, int argument) {
    return (int) (Math.log(argument) / Math.log(base));
}

但是也許您已經知道了這一點,因為您將方法命名為正確的。

計算結果為1或更大時可以將參數除以基數的次數:

public static int log(int base, int argument) {
  int result;
  for (result=0; argument>=1 ; result++) {
    argument = argument/base;
  }
  return result;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM