Finding factors of a given integer

前端 未结 14 1324
终归单人心
终归单人心 2020-12-16 19:52

I have something like this down:

int f = 120;
for(int ff = 1; ff <= f; ff++){
    while (f % ff != 0){            
}

Is there anything w

相关标签:
14条回答
  • 2020-12-16 20:04

    Utilizing Streams introduced in Java 8, the following will print the factors for a given number.

    int input = 1500;
    IntStream.rangeClosed(1, input)
             .filter(e -> input % e == 0)
             .forEach(System.out::println);
    
    0 讨论(0)
  • 2020-12-16 20:05

    This is how you write it yourself like a boss. Needs to add if statements to handle one and two, but besides that; this method is as sexy as it gets

      public static void primerize(int n){
      boolean reduced = false;
      while(n > 2){
         if(n%2 == 0){
            System.out.println(2 + "," + n/2);
            n /= 2;
         }
         else{
            int i = isPrime(n); 
            if(i == n && reduced == false){
               System.out.println(1 + "," + n);
               n /= n;
            }
            else if(i == n){
               n/= n;
            }
            else{
               System.out.println(i + "," + n/i);
               n = i;
               reduced = true;
            }
         }
      }}
    
    
    
    public static int isPrime(int n){
      for(int i = (n/3); i > 0; i--){
         if(i == 1){
            return n;
         }
         else if(n%i == 0){
            return i;
         }
      }
      return 0;}
    
    0 讨论(0)
  • 2020-12-16 20:08
        import java.util.Scanner;
        public class Factors 
        {
            Scanner scn=new Scanner(System.in);
            int num=scn.nextInt();
            public void findFactor()
            {
               System.out.println("Factors are");
               System.out.println("1");
               for(int i=2;i<=num;i++)
               {
                    if(num%i==0)
                    {
                        num=num/i;
                        System.out.println(i);
                        i=2;
                    }
               }
            }
    public static void main(String[] args) 
    {
        while(1==1)
        {
            System.out.println("Enter a Number");
            Factors fct=new Factors();
            fct.findFactor();
        }
    }
    

    }

    0 讨论(0)
  • 2020-12-16 20:13

    The following code will return a list of all factors of a given number:

    public ArrayList<Integer> findFactors(int num) {        
        ArrayList<Integer> factors = new ArrayList<Integer>();
    
        // Skip two if the number is odd
        int incrementer = num % 2 == 0 ? 1 : 2;
    
        for (int i = 1; i <= Math.sqrt(num); i += incrementer) {
    
            // If there is no remainder, then the number is a factor.
            if (num % i == 0) {
                factors.add(i);
    
                // Skip duplicates
                if (i != num / i) {
                    factors.add(num / i);
                }
    
            }
        }
    
        // Sort the list of factors
        Collections.sort(factors);
    
        return factors;
    }
    

    This answer improves Sharad Dargan's answer in two ways:

    1. Based on an idea used in this answer, you can speed up the solution by determining the value to increment by, based on whether the number is even or odd.

      Add the following line of code before the for loop:

      int incrementer = num % 2 == 0 ? 1 : 2;
      

      Then change the last part of the loop to:

       i += incrementer
      

      If the number is odd, it then will skip all even numbers, rather than always incrementing by one no matter what.

    2. Sharad stores the upper limit value in a variable and then uses that variable in the for loop:

      int upperlimit = (int)(Math.sqrt(a));
      ...
      for(int i = 1; i <= upperlimit; i+= 1)
      

      Instead, place Math.sqrt(num) directly in the for loop and skip the upper limit variable:

      for (int i = 1; i <= Math.sqrt(num); i += incrementer) {
      

      This will allow you to skip the casting part of the code, creating cleaner code.


    Some JUnit test cases you can then use:

    @Test
    public void test12() {
        FindFactors find = new FindFactors();
    
        int num = 12;
        List<Integer> factors = Arrays.asList(1, 2, 3, 4, 6, 12);
    
        assertEquals(factors, find.findFactors(num));
    }
    
    @Test
    public void test1000000() {
        FindFactors find = new FindFactors();
    
        int num = 1000000;
        List<Integer> factors = Arrays.asList(1, 2, 4, 5, 8, 10, 16, 20, 25, 32, 40, 50, 64, 80, 100, 125, 160, 200,
                250, 320, 400, 500, 625, 800, 1000, 1250, 1600, 2000, 2500, 3125, 4000, 5000, 6250, 8000, 10000, 12500,
                15625, 20000, 25000, 31250, 40000, 50000, 62500, 100000, 125000, 200000, 250000, 500000, 1000000);
    
        assertEquals(factors, find.findFactors(num));
    }
    
    @Test
    public void test1() {
        FindFactors find = new FindFactors();
    
        int num = 1;
        List<Integer> factors = Arrays.asList(1);
    
        assertEquals(factors, find.findFactors(num));
    }
    
    @Test
    public void test0() {
        FindFactors find = new FindFactors();
    
        int num = 0;
        List<Integer> factors = new ArrayList<Integer>();
    
        assertEquals(factors, find.findFactors(num));
    }
    
    0 讨论(0)
  • 2020-12-16 20:16

    Here is how to get all factors of the given number.

    public class Factors {
    
        public static void main(String[] args){
            int n = 420;
    
            for(int i=2; i<=n; i++){
                while(n%i==0){
                    System.out.println(i + "| " + n);
                    System.out.println(" -----");
                    n = n/i;
                }
            }
        }
    }
    

    Output:

    2| 420
     -----
    2| 210
     -----
    3| 105
     -----
    5| 35
     -----
    7| 7
     -----
    
    0 讨论(0)
  • 2020-12-16 20:17

    There's nothing wrong with your for loop, but a while loop is the wrong thing to be using here. The logic of your for loop is:

    • Set ff to 1.
    • Keep going while ff <= f.
    • After you've done everything in the for loop, add 1 to ff.

    This looks like it is exactly as you want.

    The while loop isn't right, though. It will continue to do whatever code you write there for as long as ff is a factor of f, so unless you change them in the while code, you'll get an infinite loop. However, changing that to an if statement will give you what you want.

    Since you're checking for factors, you don't actually need to check all possibilities up to f - only up to the square root of f. Whenever you find that ff is a factor, output both ff and f/ff as factors, unless f is a sqare number.

    0 讨论(0)
提交回复
热议问题