给定一个数“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 java.io.*; import java.math.*; class GFG { // Function to count // the divisors static void countDivisors( int n) { // Initialize count // of divisors int count = 0 ; // Note that this // loop runs till // square root for ( int i = 1 ; i <= Math.sqrt(n) + 1 ; i++) { if (n % i == 0 ) // If divisors are // equal increment // count by one // Otherwise increment // count by 2 count += (n / i == i) ? 1 : 2 ; } if (count % 2 == 0 ) System.out.println( "Even" ); else System.out.println( "Odd" ); } // Driver program public static void main(String args[]) { System.out.println( "The count of divisor:" ); countDivisors( 10 ); } } /* This code is contributed by Nikita Tiwari.*/ |
输出:
The count of divisor: Even
高效的解决方案: 我们可以观察到,只有在完全平方的情况下,除数的数目才是奇数。因此,最好的解决方案是检查给定的数字是否为完全平方。如果它是一个完美的正方形,那么除数的数量将是奇数,否则它将是偶数。
// Java program for // Efficient Solution to find // if count of divisors is // even or odd import java.io.*; import java.math.*; class GFG { // Function to find if count // of divisors is even or // odd static void countDivisors( int n) { int root_n = ( int )(Math.sqrt(n)); // If n is a perfect square, // then, it has odd divisors if (root_n * root_n == n) System.out.println( "Odd" ); else System.out.println( "Even" ); } /* Driver program to test above function */ public static void main(String args[]) throws IOException { System.out.println( "The count of " + "divisors of 10 is: " ); countDivisors( 10 ); } } /* This code is contributed by Nikita Tiwari. */ |
输出:
The count of divisors of 10 is: Even
请参阅完整的文章 检查除数的计数是偶数还是奇数 更多细节!
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END