zoukankan      html  css  js  c++  java
  • 质因子分解

    #include<iostream>
    #include<math.h>
    using namespace std;
    //所谓质因子分解:将一个正整数n分解为一个或多个质数乘积的形式
    const int maxn = 100001;
    int prime[maxn], pNum = 0;//prime表示素数,pNume表示个数
    bool p[maxn] = { 0 };
    int cnt = 0;//factor个数
    struct factor
    {
    	int x, cnt;//x表示质数,cnt表示指数
    }fac[10];
    
    //枚举1-sqrt(n)范围内的质因子,如果是因子,就在fac中增加,并且除以其
    //如果n!=1,将n放进去。
    void Find_Prime(int n)
    {
    	for (int i = 2; i < maxn; i++)
    	{
    		if (p[i] == false)
    		{
    			if (i > n)
    			{
    				return;
    			}
    			prime[pNum++] = i;
    			for (int j = i + i; j < maxn; j+=i)
    			{
    				p[j] = true;
    			}
    		}
    	}
    }
    int main()
    {
    	int n;
    	scanf("%d", &n);
    	if (n == 1)
    	{
    		printf("1=1
    ");
    		return 0;
    	}
    	printf("%d=", n);
    	int x = (int)sqrt(n * 1.0);
    	Find_Prime(x);
    	for (int i = 0; i < pNum; i++)
    	{
    		
    		if (n % prime[i] == 0)
    		{
    			fac[cnt].x = prime[i];
    			fac[cnt].cnt = 0;
    			while (n % prime[i] == 0)
    			{
    				fac[cnt].cnt++;
    				n /= prime[i];
    			}
    			cnt++;
    		}
    	}
    	if (n != 1)
    	{
    		fac[cnt].x = n;
    		fac[cnt].cnt = 1;
    		cnt++;
    	}
    	//输出
    	for (int i = 0; i < cnt-1; i++)
    	{
    		if(fac[i].cnt!=1)
    			printf("%d^%d*", fac[i].x, fac[i].cnt);
    		else
    			printf("%d*", fac[i].x);
    		
    	}
    	if (fac[cnt - 1].cnt != 1)
    		printf("%d^%d
    ", fac[cnt - 1].x, fac[cnt - 1].cnt);
    	else
    		printf("%d
    ", fac[cnt - 1].x);
    	return 0;
    }
    
  • 相关阅读:
    Entity SQL 初入
    ObjectQuery查询及方法
    Entity Framework 的事务 DbTransaction
    Construct Binary Tree from Preorder and Inorder Traversal
    Reverse Linked List
    Best Time to Buy and Sell Stock
    Remove Duplicates from Sorted Array II
    Reverse Integer
    Implement Stack using Queues
    C++中const限定符的应用
  • 原文地址:https://www.cnblogs.com/code-fun/p/15219987.html
Copyright © 2011-2022 走看看