Lintcode 235: Prime Factorization

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/roufoo/article/details/80321963

**当n为质数时,时间复杂度最低: O(sqrt(n)), 但空间复杂度最低: O(1)。
当n为2的幂时,时间复杂度最低: O(logn), 但空间复杂度最高: O(logn)。**
因为当n质因数很多时,需要空间大。当n是2的幂时,质因子最多。比如说1024=2*2*2*2*2*2*2*2*2*2。

代码如下:

#include <iostream>
#include <vector>
#include <cmath>

using namespace std;

vector<int> primeFactorization(int n) {
     vector<int> result;
     if (n<=1) return result;
     int sq=sqrt(n);
     for (int i=2; i<=sq; ++i) {
         if (n==1) return result;
         while((n%i==0) && (n>1)) {
            result.push_back(i);
            n=n/i;
         }
     }
     if (n!=1) result.push_back(n);
}

int main()
{
    vector<int> ret1=primeFactorization(10);
    for (auto i : ret1) cout<<i<<" ";
    cout<<endl;

    vector<int> ret2=primeFactorization(660);
    for (auto i : ret2) cout<<i<<" ";
    cout<<endl;

    vector<int> ret3=primeFactorization(1024);
    for (auto i : ret3) cout<<i<<" ";
    cout<<endl;

    return 0;
}

Factorization

08-27

Problem DescriptionnLMY and YY are mathematics lovers. They like to find and solve interesting mathematic problems together. One day, they found that the polynomial “x^n-1” can be factorized into a large number of long polynomials, although the polynomial “x^n-1” looks simple. They were interested in how to factorize it into irreducible polynomials.nnBy “irreducible” we mean that it has co-prime coefficients and cannot be further factorized.nnNow your task is to help LMY and YY to factorize x^n-1 into several irreducible polynomials over the integers.n nnInputnThe input consists of multiple test cases.nFor each test case, there is one line containing only one integer N. (2<=N<=1001)nnEnd of input is indicated by a line containing a zero.n nnOutputnFor each test case, output the factorization of the given polynomial according to the writing habit, i.e. x^5, 5x^2, 3x, x^2-x.nnThere are multiple ways to express the factorization of a polynomial. To make it unique, we sort the irreducible polynomials according to the following rules:nnLower order polynomials are always lexicographically smaller than higher order polynomials. Same order polynomials should be sorted by their coefficients. We compare the coefficients from high degree terms to low degree terms, including the omitted terms, which the coefficients are regard as 0. Coefficients are being compared first by absolute value then by sign. Smaller absolute values are lexicographically smaller. For the same absolute value, negative coefficients are lexicographically smaller than positive coefficients.n nnSample Inputn2n3n4n5n6n12n256n0n nnSample Outputn(x-1)(x+1)n(x-1)(x^2+x+1)n(x-1)(x+1)(x^2+1)n(x-1)(x^4+x^3+x^2+x+1)n(x-1)(x+1)(x^2-x+1)(x^2+x+1)n(x-1)(x+1)(x^2+1)(x^2-x+1)(x^2+x+1)(x^4-x^2+1)n(x-1)(x+1)(x^2+1)(x^4+1)(x^8+1)(x^16+1)(x^32+1)(x^64+1)(x^128+1)

没有更多推荐了,返回首页

私密
私密原因:
请选择设置私密原因
  • 广告
  • 抄袭
  • 版权
  • 政治
  • 色情
  • 无意义
  • 其他
其他原因:
120
出错啦
系统繁忙,请稍后再试