网易编程-最大的奇数约数c++实现

1、题目描述

小易是一个数论爱好者,并且对于一个数的奇数约数十分感兴趣。一天小易遇到这样一个问题: 定义函数f(x)为x最大的奇数约数,x为正整数。 例如:f(44) = 11.
现在给出一个N,需要求出 f(1) + f(2) + f(3).......f(N)
例如: N = 7 
f(1) + f(2) + f(3) + f(4) + f(5) + f(6) + f(7) = 1 + 1 + 3 + 1 + 5 + 3 + 7 = 21
小易计算这个问题遇到了困难,需要你来设计一个算法帮助他。 
输入描述:
输入一个整数N (1 ≤ N ≤ 1000000000)
输出描述:
输出一个整数,即为f(1) + f(2) + f(3).......f(N)


首先一看,不难,动手编起来。

#include <iostream>
#include <math.h>
using namespace std;
int main()
{
	int MaxOddNum(int x);
	int N,sum=0;
	cin>>N;
	for (int j=1;j<=N;j++)
	{
		sum+=MaxOddNum(j);
	}
	cout<<sum<<endl;
	return 0;
}
int MaxOddNum(int x)
{
	if(0!=x%2)//除以2的余数不为0,说明被除数是奇数
		return x;
	int MaxOdd=1;
	int a;
	for (int i=1;i<=sqrt(double(x));i++)
	{
		if (x%i==0)//说明此时i是x的一个约数
		{
			a=x/i;//计算i的另一个约数
			if((0!=i%2)&&(i>MaxOdd))
				MaxOdd=i;

			if((0!=a%2)&&(a>MaxOdd))//如果这个约数又是奇数
				return a;
		}	
	}
	return MaxOdd;
}


却运行时间太长,循环太多。

修改如下

#include <iostream>
using namespace std;
int main()
{

	long long N,sum=0;
	cin>>N;
	while (N)
	{
		if (1==N%2)
		{
			sum+=(1+N)*(1+N)/4;
			N=N/2;
		}
		else
		{
			sum+=N*N/4;
			N=N/2;
		}

	}
	cout<<sum<<endl;
	return 0;
}


原文地址:https://www.cnblogs.com/fushuixin/p/7413207.html