正如主题所示,我提出了下面提出的解决方案,但我觉得它很愚蠢,可以用更有效的方式重写。
请给我一些反馈或建议。
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]}");
}
}
}