Google 表格应用程序脚本。检查数字是否为质数的函数
Google Sheets Apps Script. Function to check if number is Prime
我一直在寻找 Google Sheets Apps Script 函数,可以在单元格 B1 中输入它来检查单元格 A1 是否包含质数。到目前为止我找不到任何东西。
我有 Excel 的 VBA 代码,但想将我的传播 sheet 移植到 Google 表格。
如有任何帮助,我们将不胜感激。
您可以只获取 https://en.wikipedia.org/wiki/Primality_test 上的代码并将其转换为应用程序脚本 - 添加一些额外的检查以查看 n 是否真的是一个有效数字。
function isprime(n) {
if(typeof n !== "number") return false;
if(Math.floor(n) !== n) return false;
if(n <= 1) return false;
if(n <= 3) return true;
if(n % 2 === 0 || n % 3 === 0) return false;
for(var i = 5; i*i <= n; i += 6) {
if(n % i === 0 || n % (i + 2) === 0) return false;
}
return true;
}
我一直在寻找 Google Sheets Apps Script 函数,可以在单元格 B1 中输入它来检查单元格 A1 是否包含质数。到目前为止我找不到任何东西。
我有 Excel 的 VBA 代码,但想将我的传播 sheet 移植到 Google 表格。
如有任何帮助,我们将不胜感激。
您可以只获取 https://en.wikipedia.org/wiki/Primality_test 上的代码并将其转换为应用程序脚本 - 添加一些额外的检查以查看 n 是否真的是一个有效数字。
function isprime(n) {
if(typeof n !== "number") return false;
if(Math.floor(n) !== n) return false;
if(n <= 1) return false;
if(n <= 3) return true;
if(n % 2 === 0 || n % 3 === 0) return false;
for(var i = 5; i*i <= n; i += 6) {
if(n % i === 0 || n % (i + 2) === 0) return false;
}
return true;
}