Reputation:
I am relatively new to programming, but I am trying to write a program that converts a number from base 10 to factorial base in order to assist me with a more challenging problem. Factorial base represents a number as the sum of factorials; for instance, 19 (base 10) = 301 (base factorial), because 3*3!+0*2!+1*1!=19. You can see a better explanation than mine at http://en.wikipedia.org/wiki/Factorial_number_system. What is the simplest way of accomplishing this for a number you can input? So far, I have been able to simply print the factorial of every number less than 10:
for (int base = 1; base < 10; base++){
int factorial = 1;
for (int i = 1; i < base; i++){
factorial = factorial*i;}
System.out.println(factorial);}
I am sure I am making numerous beginner mistakes; but I greatly appreciate any help you can give me for this. Thank you for your time, and for any assistance you can provide.
Upvotes: 0
Views: 1050
Reputation: 14276
for (int base = 1; base < 10; base++);{
You shouldn't have a semicolon between the for statement and the open brace. The compiler is interpreting it as if you meant
for (...) { /* empty block */ }
{ // new, unrelated block
...
}
For the actual implementation, you can look to the Wikipedia article:
For instance, one can convert a number into factorial representation producing digits from right to left, by repeatedly dividing the number by the place values (1, 2, 3, ...), taking the remainder as digits, and continuing with the integer quotient, until this quotient becomes 0.
So something like (untested, psuedocodey)...
int number = 463;
int radix = 1;
String result = ""; // prob use int[] or list in real life?
while (number > 0) {
int div = number / radix;
int remainder = number % radix;
result = remainder + result;
number = div;
++radix;
}
Upvotes: 1
Reputation: 720
Try this
public int convertToFactorial(int x10){
int length = String.valueOf(x10).length();
String[] vals = String.valueOf(x10).split("");
int result = 0;
for (int base = 1; base < length + 1; base++){
int factorial = 1;
for (int i = vals.length - base; i > 0; i--){
factorial = factorial*i;
}
result += Integer.parseInt(vals[base]) * factorial;
}
System.out.println(result);
return result;
}
P.s. look at java code convention ant language structures, you shouldn't write ; after loop defenition.
Upvotes: 1