-1

This is my code and I do not know why the answer after 12 are incorrect. First i calculate the Factorial of input number then I have to show the least valuable digit.

   
public class q3411 {
    public static int leastValuableDigit(int n) {
        for(int i = 0; i < String.valueOf(n).length(); i++) {
            int x = (int) Math.floor((n % Math.pow(10, i + 1)) / Math.pow(10, i));
            if(x != 0) return x;
        }

        return -1;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();

        int fon = 1;

        for(int i = 1; i <= n; i++) fon *= i;

        System.out.println((leastValuableDigit(fon)));
    }
}

Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52
Thomas
  • 25
  • 4

1 Answers1

0

First, I changed the algorithm of finding the factorial for more numbers. The algorithm of finding the required number can be changed by removing all 0 from the factorial and taking the last of its bytes.

    import java.math.BigInteger;
    import java.util.Scanner;
    
    public class Main {
        public static byte leastValuableDigit(BigInteger n) {
            String num = String.valueOf(n).replaceAll("0", "");
            return Byte.parseByte(String.valueOf(num.charAt(num.length() - 1)));
        }
        
        public static BigInteger getFactorial(int f) {
            if (f <= 1) {
                return BigInteger.valueOf(1);
            }
            else {
                return BigInteger.valueOf(f).multiply(getFactorial(f - 1));
            }
        }
        
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            int n = sc.nextInt();
    
            BigInteger fon = getFactorial(n);
    
            System.out.println((leastValuableDigit(fon)));
        }
    }

Your algorithm is incorrect, cause you do a lot of unnecessary calculations and roundings

Dareten
  • 165
  • 1
  • 10
  • Might be better to assist/guide rather than do their homework; YMMV. – Dave Newton Nov 08 '20 at 13:49
  • 1
    You may want to check out a better way to find the number of trailing zeros [here](https://stackoverflow.com/a/60714183/1552534). Essentially, if `n` is the target factorial, then summing the int quotients of dividing `n` by 5 until `n` == 0 is preferred over `String.replaceAll()` – WJS Nov 08 '20 at 16:12