Check if BigInteger is not a perfect square

后端 未结 6 1708
悲&欢浪女
悲&欢浪女 2020-12-29 14:12

I have a BigInteger value, let\'s say it is 282 and is inside the variable x. I now want to write a while loop that states:

while b2 isn\'t a perfect square:         


        
6条回答
  •  我在风中等你
    2020-12-29 14:38

    using System.Numerics; // needed for BigInteger
    
    /* Variables */
    BigInteger a, b, b2, n, p, q;
    int flag;
    
    /* Assign Data */
    n = 10147;
    a = iSqrt(n);
    
    /* Algorithm */
    do
    {   a = a + 1;
        b2 = (a * a) – n;
        b = iSqrt(b2);
        flag = BigInteger.Compare(b * b, b2);
    } while(flag != 0);
    
    /* Output Data */
    p = a + b;
    q = a – b;
    
    
    /* Method */
        private static BigInteger iSqrt(BigInteger num)
        { // Finds the integer square root of a positive number            
            if (0 == num) { return 0; }     // Avoid zero divide            
            BigInteger n = (num / 2) + 1;   // Initial estimate, never low            
            BigInteger n1 = (n + (num / n)) / 2;
            while (n1 < n)
            {   n = n1;
                n1 = (n + (num / n)) / 2;
            }
            return n;
        } // end iSqrt()
    

提交回复
热议问题