第三届新手赛最后一题,当时正在做Walk This Way,并且因为粗心被卡住了,刷新页面时发现此题AC数较高,转攻此题。因为时间紧迫,分秒必争,代码写得相当混乱,思路也很不清晰,各种字符的控制输出也是复制部分代码粘贴而来。第一次TLE后,误认为质数寻找效率太低,改用素数筛选法,但在数组大小问题上又陷入僵局……后经队友提醒,抛弃素数筛选,回归暴力,在第一次代码的基础上将cout换成printf,终于AC。
赛后重写代码时,发现若将质因子的上限从sqrt(N)改为N/2,时间会从0sec激增到0.9sec,这部分要加以注意。
Run Time: 0sec
Run Memory: 304KB
Code length: 1122Bytes
Submit Time: 2011-12-21 22:59:22
// Problem#: 4481
// Submission#: 1107395
// The source code is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License
// URI: http://creativecommons.org/licenses/by-nc-sa/3.0/
// All Copyright reserved by Informatic Lab of Sun Yat-sen University
#include <cstdio>
#include <cmath>
using namespace std;
int main()
{
int N, temp;
int p, a;
while ( scanf( "%d", &N ) && N ) {
printf( "%d=", N );
temp = N;
p = 2;
a = 0;
while ( temp % p != 0 && p <= sqrtf( N ) )
p++;
while ( temp % p == 0 ) {
a++;
temp /= p;
}
if ( a != 0 ) {
printf( "%d", p );
if ( a != 1 )
printf( "^%d", a );
a = 0;
}
p = ( p == 2 ? p + 1: p + 2 );
while ( p <= sqrtf( N ) ) {
if ( temp % p == 0 ) {
a++;
temp /= p;
}
else {
if ( a != 0 ) {
printf( "*%d", p );
if ( a != 1 )
printf( "^%d", a );
a = 0;
}
p += 2;
}
}
if ( temp == N )
printf( "%d", temp );
else if ( temp != 1 )
printf( "*%d", temp );
printf( "\n" );
}
return 0;
}
本文分享了一次编程竞赛经历中遇到的挑战和解决方案,重点讲述了如何优化质因数分解算法,从时间复杂度和内存使用角度进行改进,最终通过使用printf替代cout实现了AC(Accepted)结果。同时,文章还提到了调整质因子查找上限对运行时间的影响,为读者提供了优化算法的实用技巧。
1109

被折叠的 条评论
为什么被折叠?



