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

    题目:

    各位在國小時都學過因數分解,都瞭解怎麼樣用紙筆計算出結果,現在由你來敎電腦做因數分解。

    因數分解就是把一個數字,切分為數個質數的乘積,如 12=2^2 * 3

    其中, 次方的符號以 ^ 來表示

    输入说明

    一個整數, 大於1 且 小於等於 1000000

    输出说明

    一個字串

    范例输入
    20
    17
    999997
    范例输出
    2^2 * 5
    17
    757 * 1321

    分析:用两个数组a,b,a[i] 和 b[i] 分别存储由小到大排序的第i个质因数及其指数。对于每一个质因数,都会一次性“提取”干净,这样,接下去最近遇到的总是质数,如果能整除当前剩下的数now,该数就是now的质因数……如此进行下去,直到候选质数超过sqrt(n)。

    代码:

     1 #include <iostream>
     2 #include <math.h>
     3 using namespace std;
     4 int a[10000],b[10000];
     5 int temp,now,tot;
     6 int main(){
     7     int n;
     8     while(cin>>n){
     9         temp=(int)((double)sqrt(n)+1);
    10         now=n;
    11         tot=0;
    12         for(int i=2;i<=temp;++i){
    13             if(now%i==0){
    14                 a[++tot]=i;
    15                 b[tot]=0;
    16                 while(now%i==0){
    17                     ++b[tot];
    18                     now/=i;
    19                 }
    20             }
    21         }
    22         if(now!=1){
    23             a[++tot]=now;
    24             b[tot]=1; 
    25         }
    26         for(int i=1;i<tot;i++){
    27             if(b[i]==1) cout<<a[i]<<" * ";
    28             else cout<<a[i]<<"^"<<b[i]<<" * ";
    29         }
    30         if(b[tot]==1) cout<<a[tot]<<endl;
    31         else cout<<a[tot]<<"^"<<b[tot]<<endl;
    32     }
    33     return 0;
    34 }
  • 相关阅读:
    bzoj [POI2015]Myjnie
    bzoj2217 [Poi2011]Lollipop
    Codeforces A Mist of Florescence
    bzoj4380 [POI2015]Myjnie
    bzoj4292 [PA2015]Równanie
    bzoj 3517翻硬币
    模块补充
    python解释器
    __file__、__name__、__dict__方法整理
    软件开发规范
  • 原文地址:https://www.cnblogs.com/tushukai/p/7392696.html
Copyright © 2011-2022 走看看