📌  相关文章
📜  用于检查除数是偶数还是奇数的Python程序

📅  最后修改于: 2022-05-13 01:56:56.408000             🧑  作者: Mango

用于检查除数是偶数还是奇数的Python程序

给定一个数字“n”,找出它的除数总数是偶数还是奇数。

例子 :

Input  : n = 10      
Output : Even

Input:  n = 100
Output: Odd

Input:  n = 125
Output: Even

一种天真的方法是找到所有除数,然后查看除数的总数是偶数还是奇数。

这种解决方案的时间复杂度为 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 

有关详细信息,请参阅有关检查除数是偶数还是奇数的完整文章!