2011-06-30 18 views
7

可能重複:
Fastest way to determine if an integer's square root is an integer任何人都知道邏輯找出一個數字是完美的正方形?

有誰知道邏輯要找出一個數是完全平方與否? (Other than Newtons Method or Synthetic Division Method

For Eg:- 4, 16, 36, 64 are Perfect Squares. 

我將會給輸入爲441,邏輯應該說無論是其完美的正方形或沒有。

這是亞馬遜採訪中提出的一個問題。

我想與做出來的任何內置函數

+4

[?什麼是好的算法,以確定是否輸入是一個完美的正方形(http://stackoverflow.com/questions/343852/whats-a-good-algorithm-to-determine-if-an-input-is-a-perfect-square) –

+1

如果技巧是在輸入本身,那麼,因爲441有一個在右邊,那麼沒辦法可能是一個完美的廣場。 –

+0

@Jalal:像81一樣不是什麼? :-) – regularfry

回答

14

沒有Math.Sqrt,甚至乘法:

static bool IsSquare(int n) 
    { 
     int i = 1; 
     for (; ;) 
     { 
      if (n < 0) 
       return false; 
      if (n == 0) 
       return true; 
      n -= i; 
      i += 2; 
     } 
    } 
+0

現在試試它沒有添加或乘法:) – Kibbee

+1

不得不說,我真的很喜歡這個算法。 – Kibbee

+1

即使從快速基準測試中,似乎使用乘法運算速度更快。 – Kibbee

3

我會問面試官的第一個問題是,「什麼是問題的限制?」也就是說,輸入數字有多大?如果它足夠小,那麼你可以只預先計算出所有完美sqaures並將其存儲在一個字典:

IDictionary<long, bool> squares = new Dictionary<long, bool>; 
for(long i = 1; i*i <= MAX_NUM; ++i) { 
    squares[i*i] = true; 
} 

然後,以找出是否一個數x是一個完美的正方形,你只需要檢查的廣場[X ]看看它是否屬實。

0

沿着這條線會發生什麼。

public Boolean IsSquare(double input) 
{ 
    double root, product; 
    Boolean isSquare,isGTInput; 

    root = 1; 
    product = 0; 
    isSquare = false; 
    isGTInput = false; 

    while (!isSquare && !isGTInput) 
    { 
     product = root * root; 
     if (product == input) 
      isSquare = true; 
     else if (product > input) 
      isGTInput = true; 

     root += 1; 
    } 

    return isSquare; 

} 
+0

這將根據我問 – Dotnet

+0

根據對不起,我不明白你在問什麼。 – Kibbee

+0

當你使用'root * root'時,會按照我詢問 – Dotnet

相關問題