# Factor Calculation in java

December 23, 2011## What is a factor in Math

A number may be made by multiplying two or more other numbers together. The numbers that are multiplied together are called factors of the final number. All numbers have a factor of one since one multiplied by any number equals that number. All numbers can be divided by themselves to produce the number one. Therefore, we normally ignore one and the number itself as useful factors.The number fifteen can be divided into two factors which are three and five.

The number twelve could be divided into two factors which are 6 and 2.

Six could be divided into two further factors of 2 and 3.

Therefore the factors of twelve are 2, 2, and 3.

If twelve was first divided into the factors 3 and 4, the four could be divided into factors of 2 and 2. Therefore the factors of twelve are still 2, 2, and 3.

There are several clues to help determine factors.

Any even number has a factor of two Any number ending in 5 has a factor of five

Any number above 0 that ends with 0 (such as 10, 30, 1200) has factors of two and five.

To determine factors see if one of the above rules apply (ends in 5, 0 or an even number).

If none of the rules apply, there still may be factors of 3 or 7 or some other number.

Source--http://www.aaamath.com/fra72ax2.htm

Now let us derive a logic to determine the factors of a number.

1. Take the number from user.

2. As the factors are non fractional so the factor range will be 1 to that number.(mathematically minus that number to plus that number say 20- the positive factors are 1->2->4->5->10->20

and negative factors are -20->-10->-5->-4->-2->-1)

3. So get a factor the main logic is to get a number which will divide the given number and keep remainder as 0.

Now after parsing the input string to integer pass to your factor calculation code.The code will look something like the below:

public void factorcal(int a) {

//pos and negs are two string to catch the factors. a is the value given by the user. You need to Handle positive and negative values.

String pos="";

String negs="";

//Handling positive value like 20

if(a>0)

{

for (int i=-a;i<=a;i++) {

if((i!=0) && (a%i)==0) {

if(i>0)

{

pos=pos+"->"+i;

}

else

negs=negs+"->"+i;

System.out.println("Thanks for the Number, " +i);

}

}

System.out.println("Thanks for the Number, " + pos);

System.out.println("Thanks for the Number, " + negs);

}

else {

//handling negative values like -20

for (int i=a;i<=-a;i++) {

if((i!=0) && (a%i)==0) {

if(i>0)

{

pos=pos+"->"+i;

}

else

negs=negs+"->"+i;

System.out.println("Thanks for the Number, " +i);

}

}

System.out.println("Thanks for the Number, " + pos);

System.out.println("Thanks for the Number, " + negs);

}

}

## 0 comments