Home > Back-end >  how to split number into pieces with remaining part
how to split number into pieces with remaining part

Time:05-23

I want to split any number to any identical pieces and the last remaining but not dividable piece will be the last piece. I wrote this code but I know that it should be more simple way to do this :) For example; 7500 divided by 2000 and the last modulus part will be the last part. Any suggestions?

public class MyClass {
public static void main(String args[]) {
  int x =7500;
  int y = 2000;
  int lastPartCount = 0;
  String result = new String();
  
  if(x%y != 0){
      lastPartCount = x%y;
  }
  
  int newx = x-lastPartCount;
  
  for(int i=1; i<=(newx/y); i  ){
      if(i == 1){//first member
          result = "part "   i   ": 0-"   y*i;
      }else
      {
          result = "part "   i   ": "   (y*(i-1))   "-"    y*i;
      }
      
      System.out.println(result);
      
      if(i == (newx/y)){//last member
          result = "part "   (i 1)   ": "   (y*(i))   "-"    x;
          System.out.println(result);
      }
  }
}

}

the result is like this:

part 1: 0-2000
part 2: 2000-4000
part 3: 4000-6000
part 4: 6000-7500

CodePudding user response:

You can simplify your code like the following:

public static void main(String args[]) {
  int x = 7500;
  int y = 2000;
  
  for (int i = 0; i < x/y; i  ) {
      System.out.println("Part "   (i 1)   ": "   y*i   " - "   y*(i 1));
  }
  if (x%y != 0) {
    System.out.println("Part "   ((x/y) 1)   ": "   (x/y)*y   " - "   x);
  }
}

(x/y)*y) is not equal to x since you divide integers, so (x/y)*y is actually the same as the "next" i of the for-loop.

CodePudding user response:

You can also try the below code:

private void test() {
        int x = 7500;
        int y = 2000;
        int j = 0;
        int newX = x;
        while (newX > y) {
            System.out.println("Part "   (j   1)   " = "   y * j     " - "   y * j);
            newX -= y;
        }
        System.out.println("Part "   (j   1)   " = "   j * y   " - "   x);
    }

CodePudding user response:

Alternative approach using two variables in your for loop and Math.min():

int x = 7500;
int y = 2000;

for (int i = 0, p = 1; i < x; i  = y, p  ) {
    System.out.printf("Part %d: %d - %d%n", p, i, Math.min(i y,x));
}
  •  Tags:  
  • java
  • Related