nowcoder Forsaken喜欢数论 (素数筛法)

本文介绍了一个关于数论函数的求和问题及其解决方案。给定一个整数n,求解∑i=1nf(i)的值,其中f(x)为x的最小质因子。通过素数筛法实现高效计算。

Forsaken喜欢数论
题目描述

Forsaken有一个有趣的数论函数。对于任意一个数xx,f(x)f(x)会返回xx的最小质因子。如果这个数没有最小质因子,那么就返回0。
现在给定任意一个nn,Forsaken想知道 ∑ i = 1 n f ( i ) \sum_{i = 1}^{n}{f(i)} i=1nf(i) 的值。

输入描述:

一个整数n。

输出描述:

一个整数代表上面的求和式的值。

示例1
输入

4

输出

7

备注

1 ≤ n ≤ 3 e 7 1≤n≤3e7 1n3e7

思路:素数筛法
#include<iostream>
#include<cstring>
#include<stack>
#include<queue>
#include<cstdio>
#include<vector>
#include<map>
#include<unordered_map>
#include<algorithm>
using namespace std;

typedef long long LL;
typedef pair<int,int> PII;
const int MOD = 1e9 + 7;
const double eps = 1e-9;
const int INF=0x3f3f3f3f;

#define PI acos(-1)
#define IO ios::sync_with_stdio(false);cin.tie(0);cout.tie(0)
#define mem(a,b) memset(a,b,sizeof(a))
#define rep(i,x) for(int i=0;i<x;++i)
#define UP(i,x,y) for(int i=x;i<=y;i++) 
#define DOWN(i,x,y) for(int i=x;i>=y;i--)


template <typename T>
void read(T &x) 
{
    x = 0;
    int f = 1;
    char ch = getchar();
    while (!isdigit(ch)) {
        if (ch == '-') f = -1;
        ch = getchar();
    }
    while (isdigit(ch)) {
        x = x * 10 + (ch ^ 48);
        ch = getchar();
    }
    x *= f;
    return;
}


const int maxn = 3e7 + 50;
bool vis[maxn];
void Solve(){
    mem(vis,0);
    LL n,ans = 0;
    read(n);
    for(LL i = 2; i <= n; i++){
        if(!vis[i]){
            ans += i;
            for(LL j = i * i;j <= n; j += i){
                if(!vis[j]){
                    vis[j] = 1;
                    ans += i;
                }
            }
        }
    }
    cout << ans << endl;
}
int main(){
    int T = 1; //cin >> T;
    for(int i = 1; i <= T; i++){
        Solve();
    }
    return 0;
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值