UVA-10392 Factoring Large Numbers

2016-08-13

UVA - 10392 Factoring Large Numbers

題目大意:求n的所有因數。

解題思路:可以直接暴力不斷從2開始跑,遇到能整除的就整除,然後再從2開始跑。

注意:如果循環中直接讓 i 從 2 循環到 n 的話,會 TLE 。所以必須得優化算法,這裏選擇讓 i 從 2 循環到 sqrt(n) 處,可以大大節省時間。

#include <iostream>
#include <cstdio>
#include <cmath>
using namespace std;

int main() {
	long long n;
	while ( scanf("%lld", &n) && n > 0 ) {
		for ( long long i = 2; i <= sqrt(n); i++) {
			if ( n % i == 0 ) {
				printf("    %lld\n", i);
				n /= i;
				i = 2;
			}
		}
		printf("    %lld\n", n);
		cout << endl;
	}
	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章