问题陈述是:
Watson gives an integer NN to Sherlock and asks him: What is the number of divisors of NN that are divisible by 2?.
Input Format
First line contains TT, the number of testcases. This is followed by TT lines each containing an integer NN.
Output Format
For each testcase, print the required answer in one line.
Constraints
1≤T≤1001≤T≤100 1≤N≤109
Sample Input :
2\n 9\n 8
Sample Output:
0\n 3
我输入了“\n”,这意味着下一个整数将在新行中。 由于超时,Hacker Rank 不会接受我的代码。请帮我优化这段 C 代码。
我的 C 代码是:
int main() {
int length,number,i,count =0;
scanf("%d",&length);
while(length--){
scanf("%d",&number);
for(i=2;i<=number/2;i++){
if(number % i == 0 && i % 2 == 0){
count = count + 1;
}
}
if(number % 2 == 0){
count = count + 1;
}
printf("%d\n",count);
count =0;
}
return 0;
}
最佳答案
下面是解决这个问题的算法:
如果数字是偶数:
从i=2运行循环直到数字的平方根,即:sqrt(number)
并增加计数> 在下面两种情况下,如果 i 除数字(number%i==0)
:
如果i为偶数
(i%2==0)
对于 q,其中
q=number/i
如果 i 不等于 q(i!=q)
并且 q 是偶数(q%2==0)
因为如果 i 除以数字,则意味着 q 也会除以(number/q=i)
它。
最后将计数加 1,因为数字也会自除。
如果数字是奇数:
计数将为0
,因为没有i(even)可以除以奇数。
int main()
{
int length,number,i,count;
scanf("%d",&length);
while(length--)
{
scanf("%d",&number);
count =0;i=2;
if(number%2==0)
{
while(i*i<=number)
{
if(number%i==0)
{
if(i%2==0)
count++;
int q=number / i;
if (i !=q && q%2==0)
count++;
}
i++;
}
count++;
}
printf("%d\n",count);
}
return 0;
}
关于c - 由于超时,Hackerrank 不接受我的代码,如何优化这一部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36369217/