如何计算{1,2,3,..........,n}的最小公倍数?

编程入门 行业动态 更新时间:2024-10-09 15:20:55
本文介绍了如何计算{1,2,3,..........,n}的最小公倍数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如何查找 {1,2,...,n} 中的 LCM ,其中 0 < n < 10001 (以最快的方式).一种方法是计算 n! /gcd(1,2,.....,n),但这会很慢,因为测试用例的数量是 t< 501 和输出应该为 LCM(n!)%1000000007

How to find LCM of {1, 2, ..., n} where 0 < n < 10001 in fastest possible way. The one way is to calculate n! / gcd (1,2,.....,n) but this can be slow as number of testcases are t < 501 and the output should be LCM ( n! ) % 1000000007

代码的含义是:

#include<bits/stdc++.h> using namespace std; #define p 1000000007; int fact[10001] = {1}; int gcd[10001] = {1}; int main() { int i, j; for( i = 2;i < 10001; i++){ fact[i] = ( i * fact[i-1]) % p; } for(i=2 ;i < 10001; i++){ gcd[i] =__gcd( gcd[i-1], i ); } int t; cin >> t; while( t-- ) { int n; cin >> n; int res = ( fact[n] / gcd[n] ); cout << res << endl; } return 0; }

但是此代码的效果不佳.为什么?

But this code is not performing as well. Why?

推荐答案

我将以完全不同的方式进行计算:{1,...,n}的LCM是所有素数p [i]<的乘积. = n,每个在功率层中(log(n)/log(p [i])).该乘积最多可被n整除,这是最小的此类数.您的主要麻烦是然后要计算素数表.

I would calculate this in completely different way: the LCM of {1,...,n} is a product of all primes p[i]<=n, each in power floor(log(n)/log(p[i])). This product is divisible by all numbers up to n, and this is the least such number. Your main trouble is to calculate table of primes then.

更多推荐

如何计算{1,2,3,..........,n}的最小公倍数?

本文发布于:2023-11-29 10:03:39,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1646087.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:最小公倍数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!