正如主题所示,我提出了下面提出的解决方案,但我觉得它很愚蠢,可以用更有效的方式重写。
请给我一些反馈或建议。
import 'dart:io';
void main() {
// the while true loop is here only so I don't have to hit RUN every time to check another nuber
while (true) {
// Prompts user for input ( on the same line )
stdout.write("Enter the number: ");
var userInput = int.parse(stdin.readLineSync()!);
int divisor;
int numberOfFactors = 0;
var listOfFactors = [];
for (divisor = 1; divisor <= userInput; divisor++) {
if (userInput % divisor == 0) {
numberOfFactors++;
listOfFactors.add(divisor);
}
}
// formats the display of end output( is that even in English? xD)
var formattedList = listOfFactors.toString().replaceAll('[', '').replaceAll(']', '');
if (numberOfFactors > 2) {
print("Provided number is not prime, and the factors are ${formattedList}");
} else {
print(
"Provided number is prime, because it has only two factors: ${listOfFactors[0]} and ${listOfFactors[1]}");
}
}
}
这是您的更优化和固定的代码:
还做了一些进一步的优化:
numberOfFactors
因为我们可以检查列表的长度listOfFactors
来查看找到了多少个因子。formattedList
使用该方法简化了创建join()
。listOfFactors
从隐式更改List<dynamic>
为显式List<int>
。