Blue Bridge Cup 1464: [Blue Bridge Cup] [basic exercises VIP] decomposition of the quality factor

The basic idea:

A typical problem solving decomposition of the quality factor. Lacks the problem;

 

key point:

1. Note Iterative use of sqrt (n) can reduce the complexity of a certain time;

2. do not specifically ordering, enumeration when the natural order;

 

#include<iostream>
#include<stdlib.h>
#include<stdio.h>
#include<vector> 
#include<string>
#include<math.h>
#include<algorithm>
#include<cstring>
using namespace std;

const int maxn = 1000000;

struct node {
	int fac=-1;
	int cnt=0;
};

bool primecharge[maxn];


void init() {
	//进行素数初始化;
	fill(primecharge, primecharge + maxn, true);
	primecharge[0] = primecharge[1] = false;
	for (int i = 2; i < maxn; i++) {
		if (primecharge[i]) {
			for (int j = i + i; j < maxn; j+=i) {
				primecharge[i] = false;
			}
		}
	}
}

void func(int n) {
	int temp = n;
	vector<node>factor;
	int sq = int(sqrt(n));
	for (int i = 2; i <= sq; i++) {
		if (n%i == 0) {
			node f;
			f.fac = i;
			while (n%i == 0) {
				//i为因子;
				n = n / i;
				f.cnt++;
			}
			factor.push_back(f);
		}
	}
	if (n != 1) {
		node f;
		f.fac = n;
		f.cnt = 1;
		factor.push_back(f);
	}
	printf("%d=",temp);
	bool flag = true;
	for (int i = 0; i < factor.size(); i++) {
		for (int j = 0; j < factor[i].cnt; j++) {
			if (flag) {
				printf("%d", factor[i].fac);
				flag = false;
			}
			else {
				printf("*%d", factor[i].fac);
			}
		}
	}
}

int main(){
	init();
	int a, b;
	cin >> a >> b;
	for (int i = a; i <= b; i++) {
		func(i);
		cout << endl;
	}
}

  

Guess you like

Origin www.cnblogs.com/songlinxuan/p/12284140.html