Results 1 to 19 of 19
  1. #1
    spidey32 is offline Member
    Join Date
    Apr 2011
    Posts
    7
    Rep Power
    0

    Unhappy Factorial in java

    Hi, im new to this forum and also Java. Im currrently doing my degree 1st year. My lecturer gave me a question on factorial and im unable to solve it.

    i need to explain why any number of threads can be executing inside of it without causing interference in the program below.


    Public int factorial (int n)
    {
    If (n<0)
    Return -1;
    Else if (n ==0)
    Return 1;
    Int result =1;
    For (i=1; i<=n;i++)
    {
    Int tem = result;
    Temp= temp *I;
    Result=temp
    }
    Return result;
    }

    Please help me to understand this and what should i do to complete it.:confused:

  2. #2
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,755
    Rep Power
    7

    Default

    What threads are you talking about? Also if you post code please make sure it is correct Java code.

  3. #3
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    looks like someone is typing on a cell phone. Are you learning threads in your class yet? Your question isn't entirely clear, can you please clarify? Also, make sure you use code tags.

    [ code]
    YOUR CODE HERE
    [/code]

  4. #4
    spidey32 is offline Member
    Join Date
    Apr 2011
    Posts
    7
    Rep Power
    0

    Default

    Im learning thread chapter in class. This is the question that my lecturer gave to me :


    Question-2
    Given the following method, explain why any number of threads can be executing inside of it without causing interference.

    Java Code:
    	Public int factorial (int n)
    	{
    	If (n<0)
    		Return -1;
    	Else if (n ==0)
    		Return 1;
    	Int result =1;
    	For (i=1; i<=n;i++)
    	{
    		Int tem = result;
    		Temp= temp *I;
    		Result=temp 
    	}
    	Return result;
    	}
    I dont really understand the program. It would be grateful if you can guide.

  5. #5
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    That code is very wrong, I am going to assume you are posting this from a cell phone and laziness is the culprit.

    I don't have an amazing understanding of threads, but my understanding is that deadlock, and other problems come from when one thread is accessing something another thread is accessing at the same time. This is just a simple method call, it is thread safe because it isn't really changing anything, it is just running a method and returning an answer. Because of this, multiple threads should be able to run it without bumping into each other.

    Like I said though, my thread understanding is far from exceptional, so others may have better explanations.

  6. #6
    santeron is offline Member
    Join Date
    Apr 2011
    Location
    Athens, Greece
    Posts
    52
    Rep Power
    0

    Default

    Don't know what all that threads you are talking about is... but I'll try to answer the factorial part... First of all I guess you know what a factorial is (if you don't read it).

    Keep consistency in your variables. Java is case sensitive so "Result" is not the same as "result". Use curly brackets to make out code blocks too... That said:
    Java Code:
    public int factorial(int n){
    	{
    	if (n < 0) {
    		return -1;
    	} else if (n == 0) {
    		return 1;
    	}
    	int result = 1;
    	for (i = 1; i <= n; i++){
    		int temp = result; // you can replace all these 
    		temp = temp * i;   // lines with a simple
    		result = temp;     // result *= i;
    	}
    	return result;
    	}
    }
    So if you know what a factorial is you should get the logic:

    Factorial applies only to positive numbers so if a negative n is given the method returns -1. This is probably for testing reasons after the method is called
    Java Code:
    if (factorial < 0) {//the method returned -1 and you should so some error handling or something}
    If n = 0 then the factorial of 0! = 1 based on theory so you just do that.

    If n > 0 then you create a loop from 1 to n and you multiply the number with itself for every increment of i. So lets say n = 5. The factorial of 5! = 1 x 2 x 3 x 4 x 5 = 120. Then you return that value.

    I'm hope I made that clear for you...

  7. #7
    spidey32 is offline Member
    Join Date
    Apr 2011
    Posts
    7
    Rep Power
    0

    Thumbs up

    Santeron,

    You have answered my question. I understand the basic knowledge on factorial but i did not understand the question. Your explanation has helped me to understand and give a basic idea on the program. I'm working on it. Will get back here if i have any problem. :)

  8. #8
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,336
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by spidey32 View Post
    need to explain why any number of threads can be executing inside of it without causing interference in the program below.
    Your method uses only its parameter(s) and its local variables; parameters and local variables are stored on a stack and every thread has its own stack so the use of those variables can never conflict with other threads.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  9. #9
    spidey32 is offline Member
    Join Date
    Apr 2011
    Posts
    7
    Rep Power
    0

    Default

    I have tried to complete the code give by my lecturer but im only getting -1 as the output. Please help me with this code :

    Java Code:
    
     public class Factorial
    {
        public static long factorial( int n )
        {
           if( n <= 0 )     
                return -1;
           if(n==0)
                 return 1;
           else
             return n * factorial( n - 1 );
         
        }
    
        public static void main( String [ ] args )
        {
            int result=0;
            int Temp;
            int temp=result;
            for( int i = 1; i <= 9; i++ )
               Temp=temp*i;
               result=temp;
               System.out.println(factorial(result));
       
            }
     
    }

  10. #10
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    The first if statement should only be true if n < 0. If it is as you have it it will never reach the termination condition you want. I don't understand why you have such a weird main method. The original method you had was correct except for some syntax problems. I thought your assignment was to explain why multiple threads can run this in parallel.

  11. #11
    spidey32 is offline Member
    Join Date
    Apr 2011
    Posts
    7
    Rep Power
    0

    Default

    Yes, i have to explain but i tried to complete the program so that i can explain it more clearly with example of output.

  12. #12
    santeron is offline Member
    Join Date
    Apr 2011
    Location
    Athens, Greece
    Posts
    52
    Rep Power
    0

    Default

    Quote Originally Posted by spidey32 View Post
    Java Code:
    public static void main( String [ ] args )
        {
            int result=0;
            int Temp;
            int temp=result;
            for( int i = 1; i <= 9; i++ )
               Temp=temp*i;
               result=temp;
               System.out.println(factorial(result)); 
            }
    }
    I seriously don't get what you have done on those two methods... When you write some code read it line by line to see what values you have in your vars. So you start you main and you have result=0, Temp not initialized and temp=result=0. You get in the loop:
    • int = 1
      Temp = temp * i = 0 * 1 = 0
      result= temp = 0
      call factorial(result)
    • int = 2
      Temp = temp * i = 0 * 2 = 0
      result = temp = 0
      call factorial(result)
    • rest of loop

    1. So first of all you never multiply with a 0 value. Initialize result = 1.
    2. Second I told you before. Temp != temp. Java is case sensitive and those two variables are totally different.
    3. Why do you keep sending variable values from one variable to another? Why don't you just write System.out.println(factorial(i));


    Quote Originally Posted by spidey32 View Post
    Java Code:
    public class Factorial{
        public static long factorial( int n )
        {
           if( n <= 0 )     
                return -1;
           if(n==0)
                 return 1;
           else
             return n * factorial( n - 1 );
        }
    Your syntax is wrong and you have a problem in logic. Let's follow this, too. 3 possible routes.
    • n is less than 0. first if is true so it returns -1
    • n is equal to 0. first if is true again(?) and returns -1. So erase the "=" from the "<=". You should also use else if and not if. It's cleaner code.
    • n is greater than 0 so else is executed... and you call factorial method again with a n-1 argument. So if n=5 you are going to call factorial(4). Following the same logic that will call factorial(3), then that will call factorial(2) which will lead to factorial(0) which is 1. Why do that?
      Just make a for loop inside else and calculate your result.
    Try reading some site or ebook on proper Java syntax. When you write an if clause use {}:
    Java Code:
    if (condition) {
    //code
    } else if (condition) {
    //code
    } else {
    /code
    }
    //else if and else are of course optional
    Correct your code and if you need any more help just ask :)
    Last edited by santeron; 04-06-2011 at 09:07 PM.

  13. #13
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    Any reason why you changed from doing it with a loop to doing it recursively?

    Also, don't worry about main just yet. Here is some pseudocode.

    Java Code:
    if n < 0
      return -1
    end if
    if n == 0
      return 1
    end if
    declare result
    loop
      multiply loop var by result and set result to answer
    end loop
    return result
    Now recursively would look like this
    Java Code:
    if n < 0
      return -1 
    end if
    if n == 0
      return 1
    end if
    else
      return value times the recursive call
    end else

  14. #14
    spidey32 is offline Member
    Join Date
    Apr 2011
    Posts
    7
    Rep Power
    0

    Default

    Guys thanks for the reply. I have one last question.

    1) explain why any number of threads can be executing inside of it without causing interference

    Java Code:
    Public int factorial (int n)
    	{
    	If (n<0)
    		Return -1;
    	Else if (n ==0)
    		Return 1;
    	Int result =1;
    	For (i=1; i<=n;i++)
    	{
    		Int tem = result;
    		Temp= temp *I;
    		Result=temp 
    	}
    	Return result;
    	}

    Is it correct if i were to say

    1) In factorial function, the current number in current loop will not be repeated and the current number will increase because the current number will be multiplied by previous number.

  15. #15
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    Check out jos's post number 8 for a good explanation.

  16. #16
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,336
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by sunde887 View Post
    Check out jos's post number 8 for a good explanation.
    I noticed it before: my replies seem to be invisible; I answer a question but the OP goes on and on ignoring my reply and asking the same question over and over again. OPs should read the replies given to them and if they don't understand the reply they should ask instead of bluntly ignoring the reply.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  17. #17
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    Agreed. However, your post seemed very simple to understand.

  18. #18
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,336
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by sunde887 View Post
    Agreed. However, your post seemed very simple to understand.
    Well, I'd say even better because the problem isn't more complex.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  19. #19
    spidey32 is offline Member
    Join Date
    Apr 2011
    Posts
    7
    Rep Power
    0

    Default

    Jos, Im sorry because im new to the forum. Your answers have helped me alot. I didnt mean to ignore your post.

    sundae 887 : Thanks you

Similar Threads

  1. factorial sum in java
    By java157 in forum New To Java
    Replies: 9
    Last Post: 03-17-2011, 10:07 AM
  2. JSP factorial of number and NumberFormatException
    By sandraW in forum JavaServer Pages (JSP) and JSTL
    Replies: 5
    Last Post: 10-12-2010, 07:46 AM
  3. Factorial console program
    By er1c550n20 in forum New To Java
    Replies: 6
    Last Post: 04-13-2010, 02:07 PM
  4. Factorial
    By Anindo in forum New To Java
    Replies: 4
    Last Post: 07-28-2009, 09:46 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •