public class Main {
public static void main(String[] args) {
// positive number
int number = 6;
System.out.print("Factors of " + number + " are: ");
// loop runs from 1 to 60
for (int i = 1; i <= number; ++i) {
// if number is divided by i
// i is the factor
if (number % i == 0) {
System.out.print(i + ",");
}
}
}
}
And my output is "1,2,3,6," but i want it like "1,2,3,6"
How can i do that?
No matter what i do it did not worked.
>Solution :
There are multiple ways to solve it. In your case since the last 'i' in the loop is always number itself, and it should be on the list since (number%number==0), you can simply do something like this:
public class Main {
public static void main(String[] args) {
// positive number
int number = 6;
System.out.print("Factors of " + number + " are: ");
// loop runs from 1 to 60
for (int i = 1; i < number; ++i) { //< instead of <=, to exclude i==number
// if number is divided by i
// i is the factor
if (number % i == 0) {
System.out.print(i + ",");
}
}
//in your case
System.out.print(number);
}
}