Write a Program to print Factors of a Negative Integer


This Java program takes a negative integer as input and then finds all the factors of that negative integer. It first uses a Scanner object to read in the integer from the user, and then it uses a for loop to iterate through all the integers between the input integer and its absolute value (i.e., the positive version of the input integer).

Inside the loop, the program checks if the current integer is equal to 0 using an if statement with a continue statement. If the current integer is not equal to 0, then the program checks if the input integer is divisible by the current integer using another if statement. If it is divisible, then the program prints the current integer as a factor of the input integer.

Overall, this program correctly finds the factors of a negative integer. However, it would be more efficient to use a while loop that only iterates up to the square root of the input integer, as factors always come in pairs. Additionally, this program does not handle the case where the user inputs 0. In this case, the program will print out "Factors Negative Integer are:" followed by nothing. A message should be added to handle this case.

Source Code

import java.util.Scanner;
class Factors_Negative
{
	public static void main(String[] args)
	{
		Scanner input = new Scanner(System.in);
		System.out.print("Enter The Negative Number :");
		int num = input.nextInt();
		System.out.println("Factors Negative Integer are: ");
		for(int i = num; i <= Math.abs(num); ++i)
		{
			if(i == 0)
			{
				continue;
			}
			else
			{
				if (num % i == 0)
				{
					System.out.println(i);
				}
			}
		}
	}
}

Output

Enter The Negative Number :-10
Factors Negative Integer are:
-10
-5
-2
-1
1
2
5
10

Example Programs