easy1:
#include <iostream>
#define ll long long
using namespace std;
ll mod = 19260817, a, b;
ll read()
{
ll res = 0;
char ch = getchar();
while (!isdigit(ch) && ch != EOF) ch = getchar();
while (isdigit(ch))
{
res = (res << 3) + (res << 1) + (ch - '0');
res %= mod;
ch = getchar();
}
return res % mod;
}
ll qmi(ll a, ll b,ll mod) {
ll res = 1;
while (b)
{
if (b & 1) res = res * a % mod;
a = a * a % mod;
b >>= 1;
}
return res;
}
int main() {
a = read();
b = read();
if (b == 0) {
cout << "Angry!" << endl;
return 0;
}
ll ans = (ll) a * qmi(b, mod - 2, mod);
cout << (ans + mod) % mod;
return 0;
}
由于题中给出的数据远超一般的数据类型,这也是刚开始导致我的代码一直超时的原因。可以字符形式读入并且逐步转化为数字。考察了快速幂,费马小定理的知识点,注意复习笔记。
easy2:
#include <iostream>
using namespace std;
int main() {
int T, l, r;
cin >> T;
while (T--)
{
cin >> l >> r;
if (l == r && l == 1) r = 2;
cout << (r - l)<<endl;
}
return 0;
}
这道题刚开始开始没有完全理解题意,也没找到规律。后来看了相关博客发现相邻的两个数即互质并且符合题意。另外有一点需要注意的是[1,1]是一个特殊的最小互质区间。
mid1:
#include <algorithm>
#include <iostream>
#include <vector>
typedef long long LL;
using namespace std;
const int MAXN = 1000007;
bool is_prime[MAXN];//大区间:统计l-r的素数数目(通过统计合数间接获取)
bool is_prime_small[MAXN];//小区间:2-sqrt(r)的素数
//区间筛法
int prime_num(LL l, LL r) {
if (l < 2)l = 2;
for (LL i = 0; i * i <= r; i++)is_prime_small[i] = true;
for (LL i = 0; i <= r - l; i++)is_prime[i] = true;
for (LL i = 2; i * i <= r; i++) {
if (is_prime_small[i]) {
for (LL j = 2 * i; j * j <= r; j += i) {//排除小区间的合数
is_prime_small[j] = false;
}
for (LL j = max(2LL, (l + i - 1) / i) * i; j <= r; j += i) {
//(l+i-1)/i为[l,r)区间内的第一个数至少为i的多少倍.
is_prime[j - l] = false;
}
}
}
//统计
int ans = 0;
for (LL i = 0; i <= r - l; i++) if(is_prime[i]) ans++;
return ans;
}
int main() {
LL L, R;
cin >> L >> R;
cout << prime_num(L, R) << endl;
return 0;
}
由于这道题测试数据的范围太大,如果简单使用埃式筛法会超时(我尝试了很多次都错误了)需要进行改进,可以对区间进行分段, 具体可见acwing数论一章。
mid2:
#include<bits/stdc++.h>
using namespace std;
int gcd(int x,int y)//求最大公因数的函数
{
if(x%y==0)return y;
return gcd(y,x%y);
}
int main()
{
int x,y,ans=0;
cin>>x>>y;
for(int p=1;p*p<=x*y;p++)//枚举p
{
if(x*y%p!=0)continue;//不符合最大公倍数的情况
int q=x*y/p;//计算q
if(gcd(q,p)==x)ans++;//符合最大公因数
}
if(x!=y)ans*=2;
cout<<ans;
return 0;
}
首先需要注意的一点是两数如果交换位置算两种情况,需要乘2,但是也需要加上特判,如果两数相等的话就不需要乘2。
hard1:
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e6+5;
int cnt[maxn];
int dp[maxn];
int a[maxn];
int main()
{
int n,m;
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
if(a[i]<=m)cnt[a[i]]++;
}
for(int i=m;i;i--)
for(int j=i;j<=m;j+=i)
dp[j]+=cnt[i];
long long ans1=-1,ans2=-1;
for(int i=1;i<=m;i++)
if(dp[i]>ans1)
ans1=dp[i],ans2=i;
cout<<ans2<<" "<<ans1<<endl;
for(int i=1;i<=n;i++)
if(ans2%a[i]==0)
cout<<i<<" ";
cout<<endl;
}
首先把所有小于m的数的个数依次记录下来(如果值本身大于m一定不会符合题意)然后就可以把这个问题转化为一个比较好操作的问题:在给定的 n 个数中找到一个数,它在 1 到 m 的范围内有最多的因数。如果存在多个这样的数,输出其中最小的一个。然后,输出这个数的所有因数。