• O(根号n/ln(根号n))时间复杂度内求n的所有因子


    O(\frac{\sqrt{n}}{ln(\sqrt{n})})复杂度内求n的所有因子,在2e9数量级比O(\sqrt{n})快10倍左右

    先用\sqrt{n}范围内的质数除n,求出n的分解质因数形式,然后爆搜求出n的所有因子,

    n范围内的质数大约有\frac{n}{ln(n)}个,所以是这个时间复杂度

    2e9范围内因子最多的数有1600个因子,爆搜的时间复杂度很小

    1. #include
    2. #define IOS ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
    3. #define endl '\n'
    4. using namespace std;
    5. typedef pair<int, int> PII;
    6. typedef long long ll;
    7. typedef long double ld;
    8. const int N = 50010;
    9. int primes[N], cnt;
    10. bool st[N];
    11. PII factor[N];
    12. int fcnt;
    13. int dive[N], dcnt;
    14. void init()
    15. {
    16. for(int i = 2; i < N; i ++)
    17. {
    18. if(!st[i])primes[cnt ++] = i;
    19. for(int j = 0; primes[j] * i < N; j ++)
    20. {
    21. st[primes[j] * i] = true;
    22. if(i % primes[j] == 0)break;
    23. }
    24. }
    25. }
    26. void dfs(int u, int num)
    27. {
    28. if(u == fcnt)
    29. {
    30. dive[dcnt ++] = num;
    31. return;
    32. }
    33. int p = factor[u].first, c = factor[u].second;
    34. for(int i = 0; i <= c; i ++)
    35. {
    36. dfs(u + 1, num);
    37. num *= p;
    38. }
    39. }
    40. int main()
    41. {
    42. IOS
    43. init();
    44. int n;
    45. cin >> n;
    46. while(n --)
    47. {
    48. int a0, a1, b0, b1;
    49. cin >> a0 >> a1 >> b0 >> b1;
    50. fcnt = 0;
    51. int d = b1;
    52. for(int i = 0; primes[i] <= d / primes[i]; i ++)
    53. {
    54. int p = primes[i];
    55. if(d % p == 0)
    56. {
    57. int c = 0;
    58. while(d % p == 0)
    59. {
    60. d /= p;
    61. c ++;
    62. }
    63. factor[fcnt ++] = {p, c};
    64. }
    65. }
    66. if(d > 1)factor[fcnt ++] = {d, 1};
    67. dcnt = 0;
    68. dfs(0, 1);
    69. int ans = 0;
    70. for(int i = 0; i < dcnt; i ++)
    71. {
    72. int x = dive[i];
    73. if(__gcd(x, a0) == a1 && (ll)x * b0 / __gcd(x, b0) == b1)ans ++;
    74. }
    75. cout << ans << endl;
    76. }
    77. return 0;
    78. }

    如果n范围小于1e8的话还可以用  log时间复杂度求质因子  的算法将求因数优化到log级别。

  • 相关阅读:
    Redis对字符串的操作汇总
    【线性代数】为什么 AA* = |A|E
    5 分钟速通 SVG
    LeetCode 热题 100 Day05
    如何学习性能测试?
    预编译、函数变量提升
    Docker入门概述
    软件产品测试的准入准出标准有哪些?
    闭包(本质,原理,构成,作用,缺点)
    一文图解爬虫_姊妹篇(spider)
  • 原文地址:https://blog.csdn.net/a1695574118/article/details/133583711