Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Factoring a number in Java - Homework

Tags:

java

As several other questions have asked on this forum, how would you go about finding the factors of a number.

Note: I have tried to understand what other people have written, please do not rehash already given answers

My code works as of right now but, for example the number 6 returns: 6.0 factored by 1.0 is 6.000 6.0 factored by 2.0 is 3.000 6.0 factored by 3.0 is 2.000 6.0 factored by 4.0 is 1.500 6.0 factored by 5.0 is 1.200 6.0 factored by 6.0 is 1.000

Is there a way to remove all the decimal numbers? I thought somehting about a "for" statement, but I don't really know how to use them.

Current Code:

public class Factoring {

public static void main(String[] args) {
    double input;
    double factor = 1;
    double factorNum;

    System.out.println("This application calculates every factor of a given number!"
            + "\nPlease enter a number: ");
    input = TextIO.getlnDouble();

    System.out.println("Original Number: " + input);

    while (input >= factor){
        factorNum = input / factor;

        System.out.print("\n" + input + " factored by " + factor + " is ");
        System.out.printf("%.3f", factorNum);
        factor++;
    }
}

}
like image 659
Jordan.McBride Avatar asked Oct 22 '13 01:10

Jordan.McBride


1 Answers

use an int in place of double. When you use double or float you get the decimals.

So your this:

    double input;
    double factor = 1;
    double factorNum;  

Should be:

    int input;
    int factor = 1;
    int factorNum;  

SSCCE

public class Factoring {
    public static void main(String[] args) {
        int number = 15;
        int factorNumber = 1;

        while(factorNumber <= number){
            if(number % factorNumber == 0){
                System.out.println(factorNumber + " is a factor of " + number);
            }
            factorNumber ++;
        }
    }
}  

Result:

1 is a factor of 15
3 is a factor of 15
5 is a factor of 15
15 is a factor of 15  

Explanation

Consider dividing the number 15 by 2 just like you would in Math class.

15 = 2 * 7.5 + 0. Your quotient is: 7.5
In programming 7.5 and 7 are different. One is a floating point number and the other is an integer or whole number as we call them.

To store floating point numbers, float or double datatypes are used. They preserve the numbers after the decimal places.
int and long on the other hand are for whole numbers and hence they do not keep the numbers after the decimal places. They do not round them up; they truncate it.

Try this:

double withDecimals = 7.5d;
int withoutDecimals = 7.5d;

and print them.
See the difference ?

like image 163
An SO User Avatar answered Oct 26 '22 20:10

An SO User