基本数学题
link.
求解约数问题:
该问题整理了一个题型的两种问题:一个数约数的个数,两个数区间内约数的个数。
一个数约数的个数
Description
mmoaay小侄子今年上初中,老师出了一道求约数个数的题目,比如8的约数有1,2,4,8共4个。
当数比较小的时候可以人工算,当n较大时就难了。
mmoaay嫌麻烦,现在让你编个程序来算。
Input
一行一个整数。最后以0结束。
Output
分别求出这些整数的约数个数,最后的0不用处理。
我们对100的因子进行整理:
100=2^2* 5^2;
对于2:可取0 1 2 同理5
则 个数为 33=9;
唯一素因子分解定理:合数a仅能以一种方式,写成如下的乘积形式:a=p1e1p2e2…prer
其中pi为素数,p1<p2<…<pr,且ei为正整数
如果正整数n分解质因子的结果为n=p1e1p2e2…prer,
则n的约数个数为: (e1+1)(e2+1)…(er+1)
所有约数之和为:(1+p1+p12+…+p1e1)*(1+p2+p22+…+p2e2) …(1+pr+pr2+…+prer)
using namespace std;
typedef long long ll;
const int maxn=1e5;
const ll _InF = -8e18;
const int n = 1e5 + 10;
int main()
{
int a,c,d,i;
while(scanf("%d",&a)&&!a==0){
d=1;
for(i=2;a!=1;i++)
{
c=1;
while(a%i==0){
c+=1;
a/=i;
}
d*=c;
}
printf("%d\n",d);
}
return 0;
}
两个数区间内约数的个数:
Description
A pretty straight forward task, calculate the number of primes between 2 integers.
Given 2 integers A ≤ B < 10 5 what’s the number of primes in range from A to B inclusive.
Note: A prime number is a positive integer greater than 1 and is divisible by 1 and itself only. For N to be prime it is enough to test the divisibility of numbers less than or equal to square root of N.
Input
As many as 1000 lines, each line contains 2 integers A and B separated by a space. Input is terminated when A = B = -1 (Do not process this line).
Output
For every line in input – except for the last line where A = B = -1 - print the number of prime numbers between A and B inclusive.
下面是本蒟蒻的代码:(本题可能存在描述错误,但我没遇到?滑稽脸)
using namespace std;
typedef long long ll;
const int maxn=1e5+10;
const ll _InF = -8e18;
const int N = 1e5 + 10;
int i,vis[maxn];
void calprime(int n)
{
int M;
M=sqrt(n);
memset(vis, 0, sizeof(vis));
vis[0] = vis[1] = 1;//排除0 和 1 的情况
for(i=2; i<=M; i++)
{
if(!vis[i])
{
for(int j=2*i; j<=n; j+=i)
vis[j] = 1;
}
}
vis[0] = 0;
for(int i=1; i<=n; i++)
if(vis[i])
vis[i] = vis[i - 1];
else
vis[i] = vis[i - 1] + 1;
}
int main()
{
calprime(N);
int a, b,c;
while(cin >> a >> b && a != -1 && b != -1)
{
if(a-1<0)//delete one by one ,
c=0;
else
c=a-1;
cout << vis[b] - vis[c] << endl;
}
return 0;
}
//made by dragon
dalao zx代码:
#include<cstdio>
#include<cmath>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
const int Max=1e5+100;
int prime[Max];
int main()
{ /*prime[1]=1;
for(int i=2;i*i<=Max;i++)
{
if(prime[i]==0)
{
for(int j=i*2;j<=Max;j++)
prime[j]+=i;
}
}*/
long long n;
while(~scanf("%lld",&n)&&n)
{
long long x=n,ans=1;
for(long long i=2;x!=1;i++)
{
long long cnt=1;
while(x%i==0)
{
x/=i;
cnt++;
}
ans*=cnt;
}
printf("%lld\n",ans);
}
return 0;
}
打表处理
算法:x^n:
link.