Java Program for Largest K digit number divisible by X

JavaObject Oriented ProgrammingProgramming

Following is the Java program for largest K digit number divisible by X −

Example

 Live Demo

import java.io.*;
import java.lang.*;
public class Demo{
   public static int largest_k(int val_1, int val_2){
      int i = 10;
      int MAX = (int)Math.pow(i, val_2) - 1;
      return (MAX - (MAX % val_1));
   }
   public static void main(String[] args){
      int val_1 = 25;
      int val_2 = 2;
      System.out.println("The largest 2 digit number divisible by 25 is ");
      System.out.println((int)largest_k(val_1, val_2));
   }
}

Output

The largest 2 digit number divisible by 25 is
75

A class named Demo contains a function ‘largest_k’ that is used to find the largest ‘k’ (val_1) digit number that can be divided by another value (val_2). Here, another variable named ‘MAX’ is defined and the difference between MAX and (MAX % val_1) is returned. The main function defines two values for ‘x’ and ‘k’ respectively. The ‘largest_k’ function is called on these values and the output is displayed on the console.

raja
Published on 07-Jul-2020 07:39:21
Advertisements