Sum of divisors
Description
mmm is learning division, she's so proud of herself that she can figure out the sum of all the divisors of numbers no larger than 100 within one day!
But her teacher said "What if I ask you to give not only the sum but the square-sums of all the divisors of numbers within hexadecimal number 100?" mmm get stuck and she's asking for your help.
Attention, because mmm has misunderstood teacher's words, you have to solve a problem that is a little bit different.
Here's the problem, given n, you are to calculate the square sums of the digits of all the divisors of n, under the base m.
But her teacher said "What if I ask you to give not only the sum but the square-sums of all the divisors of numbers within hexadecimal number 100?" mmm get stuck and she's asking for your help.
Attention, because mmm has misunderstood teacher's words, you have to solve a problem that is a little bit different.
Here's the problem, given n, you are to calculate the square sums of the digits of all the divisors of n, under the base m.
Input
Multiple test cases, each test cases is one line with two integers.
n and m.(n, m would be given in 10-based)
1≤n≤10 9
2≤m≤16
There are less then 10 test cases.
n and m.(n, m would be given in 10-based)
1≤n≤10 9
2≤m≤16
There are less then 10 test cases.
Output
Output the answer base m.
Sample Input
10 2 30 5
Sample Output
110 112
Hint
Use A, B, C...... for 10, 11, 12......
Test case 1: divisors are 1, 2, 5, 10 which means 1, 10, 101, 1010 under base 2, the square sum of digits is
1^2+ (1^2 + 0^2) + (1^2 + 0^2 + 1^2) + .... = 6 = 110 under base 2.
题目描述:
输入n,m,n是一个十进制数,m代表m进制,将n对应的可整除的因子转换为m进制,然后将每个因子转换后的各个数字的每一位平方相加,得到的和最后再转化成m进制的数字输出。如上述例子。
分析:
题目整体不难,主要是注意细节的实现。直接全部枚举会导致超时,所以只能枚举到根号n,得到较小整除数的同时得到另一个可整除的数,同时转化累加。
平方求和的时候不需要完全转化为m进制,可通过下面步骤:
while(1)
{
sum +=(num%m)*(num%m);
num/=m;
if(num==0) break;
}
{
sum +=(num%m)*(num%m);
num/=m;
if(num==0) break;
}
累加每个因子的各位平方和以后,要转化为m进制输出。转化方式:建立一个数组,每次将对m求余存起来,然后倒过来输出。注意大于10进制的数字要用字母表示。所以选择字符串形式输出。
AC代码:
#include<iostream>
#include<string>
#include<stdio.h>
#include<algorithm>
#include<cmath>
using namespace std;
int i,num,num2,he;
int get(int num0,int d2)
{
int sum1=0;
int sq = sqrt(num0*1.0);
for(i=1;i<=sq;i++)
{
if(num0%i==0)
{
num=i;
num2 = num0/i;
he=0;
while(1) //转换进制 ,十进制转换为n进制
{
he +=(num%d2)*(num%d2);
num/=d2;
if(num==0) break;
}
sum1+=he;
if(num2 != i)
{
he=0;
while(1) //转换进制 ,十进制转换为n进制
{
he +=(num2%d2)*(num2%d2);
num2/=d2;
if(num2==0) break;
}
sum1+=he;
}
}
}
return sum1;
}
int main()
{
int n,m;
while(scanf("%d%d",&n,&m)!=EOF)
{
int a = get(n,m);;
int bit[100];
int temp=0;
while(a)
{
bit[temp++]=a%m;
a/=m;
}
for(int i=temp-1;i>=0;i--)
{
if(bit[i]>9)
printf("%c",bit[i]-10+'A');
else
printf("%d",bit[i]);
}
printf("\n");
}
// system("pause");
return 0;
}