- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我最近遇到了这个问题:
There is a (increasingly) sorted array formed by multiplying any two or more consecutive natural numbers.
2, 6, 12, 20, 24, 30, 42, 56, 60, 72 ...
Ex. 2 is formed by two consecutive natural numbers 1 and 2: 2 = 1×2. And 6 = 2×3 OR 1×2×3, 20 = 4×5.
If n is given as a parameter, find the nth number from the above array and return.
Limitation
- 1 ≤ n ≤ 1000000
- n is given only when the answer is smaller than 1012
function solution(n) {
// Find all possible product subsets of [1, ..., n] = [1x2, 2x3, 4x5, ..., 1x2x...xn]
// return Nth index of this product subset array
// 1 ~ n+1 array
const nums = Array.from({ length: n+1 }, (_, i) => i + 1);
const set = new Set();
// Find all possible product subsets
for (let i = 0; i < nums.length; i++) {
let accu = 1;
for (let j = i; j < nums.length; j++) {
accu *= nums[j];
if (i !== j) set.add(accu);
}
}
// Sort and return n-1 index value
return Array.from(set).sort((a,b) => a - b)[n-1];
}
谢谢您的帮助 :)
最佳答案
以下实现基于最小堆(C++ 中的 std::priority_queue
),它记住“最佳” future 候选者。
重要的一点是对待基本解决方案k *(k+1)
不同。由于这些数字可能占大多数,因此可以大大减少堆的大小。
在每个给定的时间,我们要么决定使用 k(k+1)
数字,或使用当前最小堆的最高值。
每个使用的值都会导致在最小堆中插入一个新的候选者。
另一方面是只在堆中插入小于估计最大值的值,n(n+1)
.
复杂度估计为 O(n log M),其中 M 是堆的平均大小。
对于 n = 10^6
,程序测得堆的最大大小等于9998,远小于n
.
在我的 PC 上,我得到了 n = 10^6
的结果在 11 毫秒内。结果:977410038240
这是 C++ 代码。
这段代码记住了所有的序列,主要是为了调试。在实践中,如果我们只需要第 n 个值,则可以避免这种内存。如果效率仍然是一个问题,则也可以删除最大堆(对调试有用)大小的度量。
#include <iostream>
#include <vector>
#include <string>
#include <queue>
#include <chrono>
template <typename T>
void print (const std::vector<T> &A , const std::string &s = "") {
std::cout << s;
for (const T& val: A) {
std::cout << val << " ";
}
std::cout << "\n";
}
struct Prod {
long long p; // product
int last; // last integer in the product
};
long long int consecutive_products (int n) {
std::vector<long long> products; // not strictly needed, for debugging
products.reserve(n);
products.push_back (2); products.push_back (6);
long long max_val = (long long) n * (n+1);
auto comp = [] (const Prod& x1, const Prod& x2) {
if (x1.p == x2.p) return x1.last > x2.last;
return x1.p > x2.p;
};
std::priority_queue<Prod, std::vector<Prod>, decltype(comp)> candidates(comp);
if (n <= 2) return products[n-1];
candidates.push ({24, 4}); // 2*3*4 -> extension of 2*3
long long int prod_simple = 12; // = 3*4 - simple products k(k-1) are dealt with differently
int rank_simple = 4;
int index = 2;
long long current_val = products[index - 1];
Prod best;
long long minval;
int max_size = 0;
while (index < n) {
if (candidates.empty()) {
minval = max_val;
} else {
best = candidates.top();
minval = best.p;
}
if (minval <= prod_simple) {
candidates.pop();
long long new_product = minval * (best.last + 1);
if (new_product < max_val) {
candidates.push ({new_product, best.last + 1});
}
} else {
minval = prod_simple;
long long new_product = prod_simple * (rank_simple + 1);
if (new_product < max_val) {
candidates.push ({new_product, rank_simple + 1});
}
prod_simple = (long long) rank_simple * (rank_simple + 1);
rank_simple++;
}
if (minval > current_val) {
products.push_back(minval);
current_val = minval;
index++;
}
int size = candidates.size();
if (size > max_size) max_size = size;
}
if (n <= 20) print (products, "Products: ");
std::cout << "max heap size = " << max_size << std::endl;
return minval;
}
int main() {
int n;
std::cout << "Enter n: ";
std::cin >> n;
auto t1 = std::chrono::high_resolution_clock::now();
auto ans = consecutive_products (n);
auto t2 = std::chrono::high_resolution_clock::now();
std::cout << ans << std::endl;
auto duration = std::chrono::duration_cast<std::chrono::microseconds>( t2 - t1 ).count();
std::cout << "duration = " << duration << " micro-s" << std::endl;
return 0;
}
关于arrays - 从由任意两个或多个连续自然数相乘形成的排序数组中查找第 N 个数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67015630/
int SIZE = 512; p = new BigInteger(SIZE, 15, new Random()); q = new BigInteger(SIZE, 15, new
我正在寻找一种方法来扩展以下形式的逻辑表达式(在字符串中): “(A或B)和((C和D)或E)” 在Python中生成所有正集的列表,即 ['A and C and D', 'A and E', 'B
我正在从 MySQL 数据库中提取一组数字,并尝试对它们进行一些简单的数学运算来计算要放入发票中的总价格,但 PHP 不配合。我认为这可能是类型强制问题,因此我尝试添加一些 intval 和 floa
给定一个包含多列字典的数据框,我如何将数据框中的键相加和/或相乘以获得一列 A B {"ab":1,
我有 2 个 UIImageView - 一个在底部并显示默认图像(如照片)- 在第二个 UIImageView 上您可以在其中绘制。 我想从两个图像创建一个 UIImage,并将其保存为新图像。 我
我有一项作业,并且我已经写完了前两部分,但我只是不知道如何找到最小的数字。我应该提到它在 jFrame (gui) 中。它应该看起来像这样: 假设我有一个数字列表 (10 5 8 7 4 9),我想知
我是 python 的新手,但是有没有办法将矩阵与 0 和符号相乘?例如,见下文: import sympy as sym import numpy as np teams=np.matrix([[1
让我们为变量赋值: thisIsANumberVariable % +5 #adds 5 to thisIsANumberVariable thisIsANumberVariable [1] 8 th
我正在尝试以下操作: Eigen::SparseMatrix bijection(2 * face_count, 2 * vert_count); /* initialization */ Eigen
我必须创建一个没有 * 或 / 运算符的乘法函数。我已经做了这样的方法。 for(int i=0; i < number1; i++){ result += number2; } System
让我们为变量赋值: thisIsANumberVariable % +5 #adds 5 to thisIsANumberVariable thisIsANumberVariable [1] 8 th
这个问题已经有答案了: Convert String to double in Java (14 个回答) 已关闭 9 年前。 我的代码有问题。所以我知道我不能将我所拥有的乘以字符串,但我真的不知道有
我正在尝试以下操作: Eigen::SparseMatrix bijection(2 * face_count, 2 * vert_count); /* initialization */ Eigen
已关闭。此问题需要 debugging details 。目前不接受答案。 编辑问题以包含 desired behavior, a specific problem or error, and the
我需要将矩阵和 vector 相乘。 为了实现这一点,我编写了一个带参数的函数: float** M 尺寸的最大值:m x n。 float* V 长度为 n 的 vector 。 float* R
我正在尝试找出一个好的循环展开来将两个矩阵相乘。 例如,如果我们想要对 NxN 矩阵求和: void SumMatrix(int *M, int n, int *result) { int i,
如果我创建一个像这样的字符串 mutiples=[1,2,3,4,5] 我希望能够使用 .forEach 将它们相乘,我该怎么做?我最好的猜测是: var total=0 multiples=[1,2
我试图将 price(1-3) 标签中的数据乘以 counterValue 以显示所选每个选项的价格 到目前为止,我的代码可以将counterValue 乘以所选选项Btn(1-3) 的因子 被选中
我有两个大小相同的 3-D 数组 a 和 b np.random.seed([3,14159]) a = np.random.randint(10, size=(4, 3, 2)) b = np.ra
关闭。这个问题需要details or clarity .它目前不接受答案。 想改进这个问题吗? 通过 editing this post 添加细节并澄清问题. 关闭 4 年前。 Improve t
我是一名优秀的程序员,十分优秀!