Kattis之旅——Prime Reduction
A prime number p≥2 is an integer which is evenly divisible by only two integers: 1 and p. A composite integer is one which is not prime. The fundamental theorem of arithmetic says that any integer x can be expressed uniquely as a set of prime factors – those prime numbers which, when multiplied together, give x. Consider the prime factorization of the following numbers:
10=2×5 16=2×2×2×2 231=3×7×11
Consider the following process, which we’ll call prime reduction. Given an input x:
if xx is prime, print xx and stop
factor xx into its prime factors p1,p2,…,pk
let x=p1+p2+⋯+pk
go back to step 1
Write a program that implements prime reduction.
Input
Input consists of a sequence of up to 2000020000 integers, one per line, in the range 22 to 109109. The number 44 will not be included in the sequence (try it to see why it’s excluded). Input ends with a line containing only the number 4.
Output
For each integer, print the value produced by prime reduction executed on that input, followed by the number of times the first line of the process executed.
Sample Input 1 | Sample Output 1 |
---|---|
2 3 5 76 100 2001 4 |
2 1 3 1 5 1 23 2 5 5 5 6 |
大意就是:给你一个数x——1、如果x是素数,直接输出x以及循环的步数。2、如果不是,那就x分解质因数,把所有质因数之和给x,步数+1,执行第一步。
//Asimple #include <bits/stdc++.h> using namespace std; typedef long long ll; ll n, m, s, res, ans, len, T, k, num;
bool is_pr(ll n) { for(int i=2; i*i<=n; i++) { if( n%i==0 ) return false; } return true; } ll solve(ll n){ ll ans = 0; int i = 2; while( n>1 ) { if( n%i==0 ) { ans += i; n /= i; if( is_pr(n) ) {//这步是关键,不写超时 ans += n; break; } } else ++i; } return ans; } void input() { while( cin >> n) { res = 1; if( n == 4 ) break; while( !is_pr(n) ) { n = solve(n); res ++; } cout << n << " " << res << endl; } } int main(){ input(); return 0; }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理