zoukankan      html  css  js  c++  java
  • 1990: 分解质因数

    #include <iostream>
    
    #include <vector>
    
    using namespace std;
    
     
    
    // 判断是否是质数
    
    bool IsPrime(int n)
    
    {
    
        int i;
    
        for (i = 2; i <= n/2; ++i)
    
        {
    
            if (n%i == 0)
    
            {
    
                return false;
    
            }
    
        }
    
        if (i > n/2)
    
        {
    
            return true;
    
        }
    
        else
    
        {
    
            return false;
    
        }
    
    }
    
     
    
    int main()
    
    {
    
        vector<int> v; // 存储2-b的所有质数
    
        int a,b;  
    
        cin >> a;
    
        cin >> b;
    
        for (int i = 2; i<=b; ++i) // 存储质数过程
    
        {
    
            if (IsPrime(i))
    
            {
    
                v.push_back(i);
    
            }
    
        }
    
     
    
        for ( int i = a; i <= b; ++i) // 从a开始处理直到b
    
        {
    
            if (IsPrime(i))   // 是质数的话 直接输出
    
            {
    
                cout << i << "=" << i;
    
            }
    
            else  // 不是质数分别处理
    
            {
    
                cout << i << "=";
    
                int temp = i;// 暂存i
    
                int index = 0; //存储质数的数组下标 索引
    
                while (temp != 1)  // 当前数字没有被除尽时继续
    
                {
    
                    if (temp%v[index] == 0)  // 从第一个质数开始除
    
                    {
    
                        cout << v[index];  
    
                        temp /= v[index];     
    
                        index = 0; // 还原   即 继续从第一个质数2开始尝试
    
     
    
                        if (temp != 1)   // 控制 * 的输出
    
                            cout << "*";
    
                    }
    
                    else  // 不能整除的话尝试下一个质数
    
                    {
    
                        index++;
    
                    }
    
     
    
                }
    
                
    
            }
    
     
    
            cout << endl;
    
        }
    
        return 0;
    
    }
    题目描述
    求出区间[a,b]中所有整数的质因数分解。 
    
    输入
    输入两个整数a,b。(2< =a< =b< =10000)  
    
    输出
    每行输出一个数的分解,形如k=a1*a2*a3...(a1< =a2< =a3...,k也是从小到大的)(具体可看样例)  
    
    样例输入
    3 10
    
    样例输出
    3=3
    4=2*2
    5=5
    6=2*3
    7=7
    8=2*2*2
    9=3*3
    10=2*5
    
    提示
    先筛出所有素数,然后再分解。
    
    
    
    
    
  • 相关阅读:
    浅析8种常用排序
    尾递归和线性递归
    线性表之顺序表
    安装minikube
    error while loading shared libraries: libatomic.so.1: cannot open shared object file: No such file or directory
    fatal error: 'openssl/conf.h' file not found
    GraphQL 最突出的架构优势是什么?
    mac 安装 brew
    Clean Architecture
    sql优化
  • 原文地址:https://www.cnblogs.com/binanry/p/9622675.html
Copyright © 2011-2022 走看看