Question

collatz public static int[] collatz(int start, int numIterations) Given integer start and integer numIterations, return an...

  • collatz

    public static int[] collatz(int start,
                                int numIterations)

    Given integer start and integer numIterations, return an array containing the Collatz sequence beginning with start up to numIterations. The Collatz function is defined by: 3n + 1 if n is odd n/2 if n is even Given start = 7 and numIterations = 3, this method returns [7, 22, 11, 34]

    Parameters:

    start - starting integer

    numIterations - how long to compute the Collatz sequence for

    Returns:

    an array containing the Collatz sequence beginning with start up to numIterations.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

public class Collatz {
   public static void main(String[] args) {
       int arr[]=collatz(7, 3);
       for(int x:arr)
           System.out.print(x+" ");
       int [][]a= {{1,2},{3,4},{5,6}};
       int sum=0;
       for(int i=0;i<a.length;i++)
           sum+=a[i][0];
       System.out.println(sum);
   }

   public static int[] collatz(int start, int numIterations) {
       int arr[] = new int[numIterations + 1];
       arr[0]=start;//first num will be starting only
      
       for (int i = 1; i < 4; i++) {
           //checking if it odd than 3n+1 else n/2
               if(start%2==1)
                   start=start*3+1;
               else
                   start=start/2;
               arr[i]=start;
       }

       return arr;
   }
}

Note : Please comment below if you have concerns. I am here to help you

If you like my answer please rate and help me it is very Imp for me

Add a comment
Know the answer?
Add Answer to:
collatz public static int[] collatz(int start, int numIterations) Given integer start and integer numIterations, return an...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
Active Questions
ADVERTISEMENT