Reputation: 161
In my code, the user enters how many numbers they want to test, and then enters the numbers. If a number can be divided by 3 distinct numbers, it prints a "1". Otherwise, it prints a "0". When I run my code, it only prints "0". I tried fixing some of the brackets to see if messed up somewhere in the syntax.
int distinct = 0;
int T = input.nextInt();
int [] nums = new int [T];
for (int n : nums) {
distinct = 0;
n = input.nextInt();
for (int m = nums.length; m == 0; m--) {
if (n % m == 0) {
distinct++;
}
}
if (distinct < 3) {
System.out.println("0");
}
else
System.out.println("1");
}
}
}
By "three distinct numbers", I mean a number like "4" which can be divided by "4, 2, and 1".
When I enter this:
3
2 3 4
It returns:
0
0
0
When it should return:
0
0
1
Upvotes: 1
Views: 224
Reputation: 1703
In the for loop, you initiate the variable with int m = nums.length
.
As the length of nums
is defined at the beginning by the user as 3, the first factor you check is 3 before checking all positive integers less than this. So, for n = 4
you check 3, 2 and 1; only 2 and 1 are factors so distinct will be 2. I suspect this should be int m = n
;
for (int m = n; m == 0; m--) {
if (n % m == 0) {
distinct++;
}
}
Assuming you are ignoring negative integers (as this would mean negative integers could be considered), the only time this will fail is when n is 1 or n is prime; 1 and n itself will always be a factor. As such, you could ignore the check for these values.
Upvotes: 1