Find Factors of a Number using Dart
In the following program, we read a number from user via console, and find all the possible factors of this number.
We store the factors in a Set.
main.dart
</>
Copy
import 'dart:io';
Set<int> factors(N) {
Set<int> result = {};
for (var i = 1; i <= N / i; ++i) {
if (N % i == 0) {
result.add(i);
result.add((N / i).floor());
}
}
return result;
}
void main() {
print('Enter N');
var N = int.parse(stdin.readLineSync()!);
var result = factors(N);
print('Factors of $N\n$result');
}
Output
Enter N
120
Factors of 120
{1, 120, 2, 60, 3, 40, 4, 30, 5, 24, 6, 20, 8, 15, 10, 12}
Summary
In this Dart Tutorial, we have written a Dart program to find all the possible factors of a given number.