Project Euler #34: Digit factorials - review code : Java -
a digital factorial need found out. no. divisible sum of factorials of digits of no. trying on hackerrank : https://www.hackerrank.com/contests/projecteuler/challenges/euler034/
my code passing 1 test case i.e. if n < 20.other test cases not passing.
code below.
import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class solution { public static void main(string[] args) { scanner sc = new scanner(system.in); int n = sc.nextint(); int len,newt=0,pos = 0,ans=0; long fac,sum; for(int i=10;i<=n;i++){ newt = i; sum =0; len = string.valueof(newt).length(); while(len>0){ fac=1; pos = newt % 10; newt = newt/10; for(int k=1;k<=pos;k++){ fac = fac*k; } sum+=fac; len--; } // system.out.print(sum+" "+i); // system.out.println(); if(sum%i==0){ ans = i; } } system.out.print(ans); } }
your code iterating digits of number n
seems overly complex. it's simple this:
if (n <= 0) throw new illegalargumentexception("not positive number: " + n); (; n > 0; n /= 10) { int digit = n % 10; // use digit here }
your code can improved using methods separate logic independent parts, e.g.
private static int sumcuriousnumbers(int n) { int sum = 0; (int = 10; <= n; i++) if (iscuriousnumber(i)) sum += i; return sum; } private static boolean iscuriousnumber(int number) { int sum = 0; (int = number; > 0; /= 10) sum += factorial(i % 10); return (sum % number == 0); } private static int factorial(int n) { int f = 1; (int = 1; <= n; i++) f *= i; return f; }
this helps document code , 3 methods can unit-tested too.
Comments
Post a Comment