我正在尝试编写一个脚本来计算所有低于X的数字的素数因子(在这个例子中为100万)。代码非常简单,我觉得很容易理解,但我似乎无法找出它为什么不起作用。
where ($number -lt 1000000) {
where ($number2 -lt $number) {
if (($number % $number2) -eq 0) {
Write-Host number $number prime $number2 >> C:\workspace\output.txt
}
}
}
答案 0 :(得分:0)
where ($number -lt 1000000) {
where ($number2 -lt $number) {
if (($number % $number2) -eq 0) {
Write-Host number $number prime $number2 >> C:\workspace\output.txt
}
$number++
}
}
你需要在循环中增加$ number
答案 1 :(得分:0)
你们都是对的。我错过了$number = $number + 1
。几个小时后我才弄清楚了。
#setup
$number = 1
$number2 = 1
while ($number -le 1000000)
{
while ($number2 -le $number)
{
if (($number % $number2) -eq 0)
{
Write-Host $number and $number2
}
$number2 = $number2 + 1
}
$number2 = 1
$number = $number + 1
}
答案 2 :(得分:0)
这是我的问题-此脚本/函数返回数字的因数
优化
Function Factorise {
PARAM ($Number)
$MaxFactor = [math]::Sqrt($Number)
#take care of 2 as a factor
$Factor=2
while ( ($Number % $Factor) -eq 0) {
$Factor
$Number=$Number/$Factor
}
#then brute force all odd numbers as factors up to max prime
#while $Number remains greater than max prime
$Factor=3
while ($Factor -le $MaxFactor -and $number -ge $MaxFactor) {
while ( ($Number % $Factor) -eq 0) {
$Factor
$Number=$Number/$Factor
}
$Factor+=2
}
$Number
}
样本输出
Factorise 32770
2
5
29
113