File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Beginners Code Problem Help Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Beginners Code Problem Help" Watch "Beginners Code Problem Help" New topic
Author

Beginners Code Problem Help

Nathan Whitaker
Greenhorn

Joined: Jul 30, 2011
Posts: 4
Ive been trying to solve a code problem that i found on some site that had Java Challenges for beginners. It was to make a program that calculated the sum of the first fifteen factorials. http://en.wikipedia.org/wiki/Factorials
this is the code ive written so far:

public class Factorials{
public static void main(String[] args){
int a;
a=1;
int b;
b=1;
b=1;
int c;
int d;
d=1+2;
if(a==1)
c=a;
if(a==2)
c=a;
else
c=a*(a-b)*(a-b++);
do{
a++;
}
while(a<15);
do{
d=d+c;
}
while(a<15);
if(a!=15)
System.out.println("Fail");
if(a==15)
System.out.println(d);
It will compile and run, but the number will be in the trillions and i keep getting an output of three...






Andrew Monkhouse
author and jackaroo
Marshal Commander

Joined: Mar 28, 2003
Posts: 11404
    
  81

You seem to have posted only some of your code. I suspect that nobody will be able to help you while the code your provide is uncompilable.

Please take a moment to learn about [code] and [/code] ubb code blocks and how to indent your code. One example of a coding style is the CodeRanch coding style - you don't have to follow it, but you should follow some style guide. Trying to read code that is not formatted is very difficult. Most people are likely to ignore your post and go on to one that is easier to read.

Code you have provided so far:

See the lack of anything following line 28? This will stop the program from compiling.


The Sun Certified Java Developer Exam with J2SE 5: paper version from Amazon, PDF from Apress, Online reference: Books 24x7 Personal blog
Andrew Monkhouse
author and jackaroo
Marshal Commander

Joined: Mar 28, 2003
Posts: 11404
    
  81

Lets look at what this code is doing:

Lines 3 & 4 can be combined into a single statement. That is

Is the same as:

Similarly with your definition for b, which is effectively:

And the same for your definition for d, which is effectively:

So now we have:

At this point we know that a is equal to one - it was defined early on, and has never been redefined. So we know that at the end of this, c = a, or c = 1. This gives us:

We know that a is still equal to one, so the test at line 8 is always going to be false, giving us:

We know that a = 1, and b = 1, therefore a-b is always going to equal zero. Since line 8 uses that as part of the multiplication, and any number multiplied by zero is zero, the end result of line 8 is that c will equal zero. Viz:

We have now incremented a 14 times. So we could write this as:

a is still equal to 15, so this loop only gets processed once. The end result is that we are adding zero to the existing 3 already stored in d.

Now we are left with:

We know that a is equal to 15 (still!) so line 11 will evaluate to false, and line 12 will never run.

a is still equal to 15, so line 13 will be true, and line 14 will print the contents of d - namely the value 3.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37884
    
  22
Welcome again.
How are you working out factorials? That looks like no factorial algorithm I have ever seen. For factorials of arguments greater than 12, you should use a long rather than an int. I think you run out of capacity in longs after about 23!
Nathan Whitaker
Greenhorn

Joined: Jul 30, 2011
Posts: 4
Campbell Ritchie wrote:Welcome again.
How are you working out factorials? That looks like no factorial algorithm I have ever seen. For factorials of arguments greater than 12, you should use a long rather than an int. I think you run out of capacity in longs after about 23!

It probably looks like no algorithm you have ever seen because i have been coding all of three days....
I seem to be missing information in every aspect of coding, including the rules on this forum according to whomever first responded if I understood his reply correctly.
Sorry for the difficulty in understanding my query. What I would like to do is have a segment of code that will calculate the sum of the previous factorials, given an input number. For the sake of this code, it is fifteen. If what I posted was completely ridiculous, it is because I have neither experience or knowledge. If I have to scrap the whole code, no problem, it was the work of fifteen minutes. Any help is appreciated.
Nathan Whitaker
Greenhorn

Joined: Jul 30, 2011
Posts: 4
Andrew Monkhouse wrote:

Please take a moment to learn about [code] and [/code] ubb code blocks and how to indent your code. One example of a coding style is the CodeRanch coding style - you don't have to follow it, but you should follow some style guide. Trying to read code that is not formatted is very difficult. Most people are likely to ignore your post and go on to one that is easier to read.

Sorry about the style, I have zero experience at both Java and Forums. I'll make sure whatever I post next is up to code.
(Pun definitely intended)
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11150
    
  16

The first several hours of writing code should be spent writing NO code at all. You should start with pencil/paper (or a text editor) writing down in ENGLISH how to computer your problem. Then you revise it. Then you revise it again. Then you revise it again. You keep doing that until there is no line that you look at and can't immediately say "I would write that in java like this". Your directions should eventually be so clear you could hand them to anyone - even someone who has never heard the term 'factorial', and they would know exactly what to do.

So, for your problem, I may start like this:

1) compute the factorials of 1-15
2) add them up.

Now, I have no idea how do do either of those in java. so, let's start by revising 1)

1a) take each number, one at a time, from 1-15
1b) computer that one number's factorial, and remember it

So that 1a...that sounds like something I could do in java, maybe with a loop of some kind. 1b...that may need some more revision.

The nice thing about programming is that it is modular. I could write the code for 1a, do some testing on it to make sure it works, then later come back and put in either a chunk of code or a method call. I'll often write dummy methods that fake what I need while I test other stuff. So I would probably (once I am at the point where I want to write code) first write a loop for getting the numbers 1-15. I'd pass them into a method that is supposed to compute that number factorial, but at first would return a string saying "I computed <the number> factorial!!!".


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Andrew Monkhouse
author and jackaroo
Marshal Commander

Joined: Mar 28, 2003
Posts: 11404
    
  81

Nathan Whitaker wrote:I seem to be missing [...] the rules on this forum according to whomever first responded if I understood his reply correctly.

Not quite as hard as rules. What I was trying to get across is that there are ways of improving your chances of getting a good response. Properly formatting code and putting that code between [code] and [/code] ubb code blocks are two ways of increasing the likelihood of getting a good response. We even have a wiki page - HowToAskQuestionsOnJavaRanch - dedicated to giving hints as to what you can do to get best results.

This is no different than spending time working on a good resume and cover letter for a job - if you don't take extra time to get this right, there is a good chance your potential employer will not take the time to read it.

I really like Fred's suggestion of breaking down the problem.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37884
    
  22
Have you got a factorial algorithm? They are really quite simple. There are two popular types: iterative and recursive. At your stage I would think you would understand an iterative type, which is actually what Fred described, much more easily than a recursive type.

Do you know how to work out a factorial on paper? Get a pencil paper and eraser and write down how to calculate a factorial. It is the product of all the natural numbers between the argument and 1 inclusive. Since the × operator is associative, you can work it out in any order. There is a definition you might need: 0! = 1
Get your description into smaller and smaller bits. When you have got it down to very small words, you can probably convert it to real code easily.
Nathan Whitaker
Greenhorn

Joined: Jul 30, 2011
Posts: 4
Thanks for all the input, it is much appreciated.
Here is the list of problems I have come up with.
a) Calculate factorial of a series of numbers, increasing by one each time
b) give first variable a definition of one
c) define another variable as the sum of the factorials of the first variable
d) take first variable and calculate the factorial
e) record with second variable
f) add one to the first variable
g) still keeping the value of the first factorial, record the value of this factorial and add it to the second variable
h) repeat until goal number is reached
Any comments, suggestions would be helpful!
Benjamin Thvedt
Ranch Hand

Joined: Jul 29, 2011
Posts: 31
why don't you like have a method that computes a factorial something like

int factorial(int x) // computes the factorial of x (might need to be a doulbe or something)
{
// Insert code for computing the factorial here...
}

Then have another for loop that sums it up in the main() like this:

int theanwser = 0;
for (int i = 0; i < 15; i++) {
theanwser += factorial(i);
}

that's how I would do it. The only question is, is the first factorial 0! or is it 1!?
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: Beginners Code Problem Help
 
Similar Threads
Public Variables
Brackets problem
methods and return type
a question about super command
a bug with a constructor