I'm solving an problem where it need to get the difference between the number of even and odd divisors ,and i need to use sqrt() function because the limit of the number is 10^9 so looping on the whole number is not an option cause of the time limit exceed.
this a function I tried to make but it doesn't work perfectly on all number.
Ex. 4 & 48745.
Case 4 : should output 2 even divisors {2,4} and 1 odd divisor {1} -- the below function output 3 even 1 odd
Case 48745 :should output 0 even divisors and 4 odd divisors {1,5,9749,48745} -- the below function output 2 even 2 odd
int di(int x)
{
int even=0,odd=0;
for(int i=1;i<=sqrt(x);i++)
{
if(x%i==0)
{
if(i%2)
odd++;
else
even++;
if(x/i %2==0 && x/i!=i)
even++;
else if(x/i!=i)
odd++;
}
}
return even-odd;
}
Try more simple code:
#include <iostream>
#include <cmath>
int divdiff(int x)
{
unsigned int even = 0;
unsigned int odd = 0;
const unsigned int sqrtx = std::sqrt(x);
for (int i = 1 ; i <= sqrtx ; ++i)
{
if (x % i == 0)
{
if (i % 2 == 0)
{
++even;
}
else
{
++odd;
}
}
}
even *= 2;
odd *= 2;
if (x == sqrtx * sqrtx)
{
if (x % 2 == 0)
{
--even;
}
else
{
--odd;
}
}
std::cerr << __func__ << '(' << x << "): even=" << even << ", odd=" << odd << std::endl;
return even - odd;
}
int main()
{
std::cout << divdiff(2*2) << std::endl;
std::cout << divdiff(2*3) << std::endl;
std::cout << divdiff(3*3) << std::endl;
std::cout << divdiff(7*11*13*17*23) << std::endl;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.