Thursday, September 4, 2025
HomeData Modelling & AIJava Program for Largest K digit number divisible by X

Java Program for Largest K digit number divisible by X

Integers X and K are given. The task is to find highest K-digit number divisible by X.

Examples:

Input : X = 30, K = 3
Output : 990
990 is the largest three digit 
number divisible by 30.

Input : X = 7, K = 2
Output : 98

An efficient solution is to use below formula.

ans = MAX - (MAX % X)
where MAX is the largest K digit 
number which is  999...K-times

The formula works on simple school method division. We remove remainder to get the largest divisible number.




// Java code to find highest
// K-digit number divisible by X
  
import java.io.*;
import java.lang.*;
  
class GFG {
    public static double answer(double X, double K)
    {
        double i = 10;
        // Computing MAX
        double MAX = Math.pow(i, K) - 1;
  
        // returning ans
        return (MAX - (MAX % X));
    }
  
    public static void main(String[] args)
    {
  
        // Number whose divisible is to be found
        double X = 30;
  
        // Max K-digit divisible is to be found
        double K = 3;
  
        System.out.println((int)answer(X, K));
    }
}
  
// Code contributes by Mohit Gupta_OMG <(0_o)>


Output:

990

To understand Math.pow() function, please refer point 18 of the article :
https://www.neveropen.co.uk/java-lang-math-class-java-set-2/

Please refer complete article on Largest K digit number divisible by X for more details!

Last Updated :
05 Dec, 2018
Like Article
Save Article


Previous

<!–

8 Min Read | Java

–>


Next


<!–

8 Min Read | Java

–>

RELATED ARTICLES

Most Popular

Dominic
32261 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6626 POSTS0 COMMENTS
Nicole Veronica
11795 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11855 POSTS0 COMMENTS
Shaida Kate Naidoo
6747 POSTS0 COMMENTS
Ted Musemwa
7023 POSTS0 COMMENTS
Thapelo Manthata
6695 POSTS0 COMMENTS
Umr Jansen
6714 POSTS0 COMMENTS