给定一个数“n”,求其除数的总数为偶数或奇数。
null
例如:
Input : n = 10 Output : Even Input: n = 100 Output: Odd Input: n = 125 Output: Even
A. 幼稚的方法 那就是 找到所有的除数 然后看看除数的总数是偶数还是奇数。
这种解决方案的时间复杂度为O(sqrt(n))
# Naive Solution to # find if count of # divisors is even # or odd import math # Function to count # the divisors def countDivisors(n) : # Initialize count # of divisors count = 0 # Note that this loop # runs till square # root for i in range ( 1 , ( int )(math.sqrt(n)) + 2 ) : if (n % i = = 0 ) : # If divisors are # equal,increment # count by one # Otherwise increment # count by 2 if ( n / / i = = i) : count = count + 1 else : count = count + 2 if (count % 2 = = 0 ) : print ( "Even" ) else : print ( "Odd" ) # Driver program to test above function */ print ( "The count of divisor: " ) countDivisors( 10 ) #This code is contributed by Nikita Tiwari.*/ |
输出:
The count of divisor: Even
高效的解决方案: 我们可以观察到,只有在完全平方的情况下,除数的数目才是奇数。因此,最好的解决方案是检查给定的数字是否为完全平方。如果它是一个完美的正方形,那么除数的数量将是奇数,否则它将是偶数。
# Python program for # Efficient Solution to find # find if count of divisors # is even or odd # Python program for # Efficient Solution to find # find if count of divisors # is even or odd def NumOfDivisor(n): if n < 1 : return root_n = n * * 0.5 # If n is a perfect square, # then it has odd divisors if root_n * * 2 = = n: print ( "Odd" ) else : print ( "Even" ) # Driver code if __name__ = = '__main__' : print ( "The count of divisor" + "of 10 is: " ) NumOfDivisor( 10 ) # This code is contributed by Yt R |
输出:
The count of divisorof 10 is: Even
请参阅完整的文章 检查除数的计数是偶数还是奇数 更多细节!
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END