Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I need help getting my code output to look like the image below and I am not sure what I am doing wrong and I need to have my code output indented and cant remember how to indent it.
Here is my code currently:
// Fig. 18.3: FactorialCalculator.java
// Recursive factorial method.
public class Assignment_6_1
{
// recursive method factorial (assumes its parameter is >= 0
static StringBuilder s = new StringBuilder();
public static long factorial(long number)
{
if (number == 0) // test for base case
{
return 1;
} else {// recursion step
if (s.length() == 0) {
s.append(number).append("*").append(number - 1);
} else {
for (int i = 0; i < s.length(); i++) {
}
System.out.println(number + " * " + (number - 1) + "!");
s.append("*").append(number).append("*").append(number - 1);
}
return number * factorial(number - 1);
}
}
// output factorials for values 0-21
public static void main(String[] args) {
System.out.println("Hannah Coffey - Lab 6");
// calculate the factorials of 0 through 20
for (int counter = 0; counter < 25; counter++) {
s = new StringBuilder();
System.out.println(counter + "!");
System.out.printf("%d! = %d%n", counter, factorial(counter));
}
}
} // end class FactorialCalculator
Here is what I need it to look like and not sure what I am doing wrong:
Any Help would be greatly appreciated.
My program currently looks like this:
enter image description here
You can pad a String using String.format like this :
String.format("%10s", "foo");
It will create a left padding of 7 spaces 7 + foo.length = 10;
Now, we can render that dynamic like :
public static String padding( int i ) {
return i == 0 ? "" : String.format( "%" + i + "s", "" );
}
Just pass the number of spaces and let the formatter do the job.
for(int i = 5; i >= 0; --i){
System.out.println(padding(i) + "i");
}
Output :
5
4
3
2
1
0
public static long factorial(long number){
if (number == 0) // test for base case
{
return 1;
} else {// recursion step
if (s.length() == 0) {
s.append(number).append("*").append(number - 1);
} else {
String spaces = "";
for (int i = 0; i < number; i++) {
spaces = spaces+" ";
}
if(number==1)
System.out.println(" Base Case: 1");
else {
System.out.println(spaces + "Recursive call:" + number + " * fact(" + (number - 1) + ")");
s.append("*").append(number).append("*").append(number - 1);
}
}
return number * factorial(number - 1);
}
}
public static void main(String[] args) {
System.out.println("Hannah Coffey - Lab 6");
// calculate the factorials of 0 through 20
for (int counter = 0; counter < 25; counter++) {
s = new StringBuilder();
for (int i = 0; i < counter; i++) {
spaces = spaces+" ";
}
System.out.println(spaces+"Recursive call:"+counter + "!");
System.out.printf("%d! = %d%n", counter, factorial(counter));
}
}
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I'm just calculating with recursive code, but it goes into infinite loop.
EDIT: Full code.
and IDE(Eclipse) says nothing about it, and it can be running well.
class RepresentWithN {
static int number;
static int N;
static int answer;
public int solution(int N, int number) {
RepresentWithN.N = N;
RepresentWithN.number = number;
answer = 9;
calc(0, 0);
return answer == 9 ? -1 : answer;
}
static int conN(int length) {
int tmp = N;
for (int i = 1; i < length; i++) {
tmp += tmp * 10;
}
return tmp;
}
static void calc(int prev, int count) {
if (count == 9) {
return;
}
if (prev == number) {
answer = Math.min(answer, count);
return;
}
System.out.println("count=" + count + " prev=" + prev);
for (int i = 1; i <= 5; i++) {
calc(prev + conN(i), count + 1);
calc(prev - conN(i), count + 1);
calc(prev * conN(i), count + 1);
calc(prev / conN(i), count + 1);
}
}
It repeated 'count' is around 7 or 8, and don't know why.
eventually count has the value 9. check this by printing this values.
static void calc(int prev, int count) {
System.out.println("count=" + count + " prev=" + prev);
if (count == 9) {
return;
}
...
There are so many branches in your recursion and that needs a huge amount of calculation. Thats why it is not ending. You can wait another hour or days/years to see the ends of this program. Or replace this code with efficient one.
Try this. After each run, uncomment one of the recursive calls.
public class ForEverDemo {
static long count = 0;
public static void main(String[] args) {
alongtime(0);
System.out.println("count = " + count);
}
public static void alongtime(int v) {
count++;
if (v == 9) {
return;
}
for (int i = 0; i < 3; i++) {
alongtime(v + 1);
// alongtime(v + 1);
// alongtime(v + 1);
// alongtime(v + 1);
// alongtime(v + 1);
}
}
}
Can anyone here please help me to reduce the time complexity of this code:
public static int a(int number) {
if ((number == 0) || (number == 1))
return number;
else
return a(number - 1) + a(number - 2);
}
public static void main(String[] args) {
System.out.print("Enter the count of Fibonacci series: ");
int cap = new Scanner(System.in).nextInt();
System.out.println("Output: ");
for (int i = 1; i <= cap; i++){
System.out.printf("%d\n", a(i));
}
}
You can store previously calculated values, so if you try calculate fibonnaci(100) you don't calculate fibonacci(50) about 100 times.
Pseudo code:
dictA = {}
a(n):
if n in dictA:
return dictA[n]
else if n <= 1:
return n
else:
val = a(n-1) + a(n-2)
dictA[n] = val
return val
It is quite simple to add some cache, where you will store already calculated values. If you want exactly the recursive algorithm the idea will be the same - just check in the beginning of routine if the value already calculated. If yes - return it from cache, else - start calculate (do not forget to save it after calculation ended).
public class Fibbonaci {
public static long calc(int n) {
List<Integer> cache = new ArrayList<>();
cache.add(1);
cache.add(2);
for (int i = 2; i < n; i++) {
cache.add(cache.get(i - 1) + cache.get(i - 2));
}
return cache.get(n - 1);
}
public static void main(String[] args) {
IntStream.range(1, 10)
.forEach(n -> System.out.println("Fibb " + n + " = " + calc(n)));
}
}
I am supposed to get this series
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
NOTE:The spaces mentioned have to be present it should have the exact same output as i have mentioned
I tried this:
class pattern_19
{
static void main()
{
int i,j;
int s=1;
System.out.println(s);
for(i=1;i<=6;i++)
{
for(j=1;j<=i;j++)
{
s=s*11;
}
System.out.println(s);
s=1;
}
}
}
MY OUTPUT:
11
121
1331
14641
161051
1771561
This did not work any help will be appreciated
Your code would not compile because your main method was not defined correctly. This is one thing but not the main reason why you were getting an unexpected output.
Your s variable represent one integer on each line.
What you'll have to do from there is split your int and print each one of the digits seperately.
Here is a correction, I used an enhanced loop and a charArray to print the digits seperately but there are other ways to achieve this of course (using a loop and integer division works also or modify the way you find s).
Solution
public static void main(String[] args) {
int i, j;
int s = 1;
System.out.println(s + " ");
for (i = 1; i <= 6; i++) {
for (j = 1; j <= i; j++) {
s = s * 11;
}
for (char c : String.valueOf(s).toCharArray()) System.out.print(c + " ");
System.out.println();
s = 1;
}
}
PS : Multiplying by 11 wont work when you'll need numbers with a length of 2. I'll edit my answer right now.
Here is the algorithm solution
public static void main(String[] args) {
int rows = 6;
int[][] triangle = new int[rows][rows];
for (int i = 1; i <= rows; i++) {
for (int j = 0; j < i; j++) {
if (j == 0) triangle[i - 1][j] = 1;
else triangle[i - 1][j] = triangle[i - 2][j - 1] + triangle[i - 2][j];
System.out.print(triangle[i - 1][j] + " ");
}
System.out.println();
}
}
I finally also got an alternative to do the same here it goes
public class PascalTriangle {
public static void main() {
int rows = 6;
for (int i = 0; i < rows; i++) {
int number = 1;
System.out.format("%" + (rows - i) * 2 + "s", "");
for (int j = 0; j <= i; j++) {
System.out.format("%4d", number);
number = number * (i - j) / (j + 1);
}
System.out.println();
}
}
}
Now this one is working properly .
I am trying to write a program that give an output as prime decomposition of a given number. However, my code gives correct answer as an output of "2**2**2**2**2**5**7**7**11*" but I want it specific output as "(p1**n1)(p2**n2)...(pk**nk)". Here's my code:
public class PrimeDecomp
{
public static String factors(int n)
{
String ans = "";
for (int i = 2; i <= n; i++)
{
if (n % i == 0)
{
// checks if i is a divisor of num
ans += i + "**";
// writes i in prime factorization
n = n/i;
// since it is written down, num=num/i
i--;
// just in case their are multiple factors of same number.
// For example, 12=2*2*3
}
}
return (ans.substring(0, ans.length() - 1));
}
public static void main(String[] args)
{
System.out.println(PrimeDecomp.factors(86240));
}
}
You almost got it, instead of computing one factor at a time, compute all for the same factor and count them:
public static String factors(int n)
{
String ans = "";
int count = 0;
for (int i = 2; i <= n; i++)
{
// Reset the counter
count = 0;
/*
* Instead of only processing on factor, we process them all and
* count them
*/
while (n % i == 0)
{
count++;
n = n / i;
}
// If we have at least processed one add it to the string
if (count == 1)
{
ans += "(" + i + ")";
} else if (count > 0)
{
ans += "(" + i + "**" + count + ")";
}
}
return ans;
}
Since you are manipulating a string quite often in a loop, you should use StringBuilder
I'm in a beginners java class and I have a quick question about the output statement on my array problem for week 5. So basically I have the core of the program down, but I'm supposed to output the result in lines of ten. I for some reason can not get it to work even with looking at similar posts on here. I'm a beginner and am pretty slow at putting 2 and 2 together when it comes to programming. Once I see it I have that ah-ha! moment and that's how this whole class has gone. I know I have to use the modulus, but in my trial and error I lost my way and have probably done more damage than good. Help would be appreciated.
Here is what I have and as you can tell I was trying something without modulus:
import java.util.*;
public class ArrayLoop
{
public static void main(String args[])
{
double alpha[] = new double[50];
*//Initialize the first 25 elements of the array (int i=0; i<25; i++)//*
for(int i = 0; i < 25; i++)
{
alpha[i]= i * i;
}
*//Initialize the last 25 elements of the array (i=25; i<50; i++)//*
for(int i = 25; i < 50; i++)
{
alpha[i]= 3 * i;
}
*//Print the element of the array*
System.out.println ( "The values are: " );
for (int i = 0; i < 50; i++)
System.out.println ( alpha[i] );
}
*//Print method to display the element of the array*
void print(double m_array[])
{
for(int i = 1; i < m_array.length; i++)
{
if(i % 10 == 0){;
System.out.println();
}else{
System.out.print(" ");
}
}
if (m_array.length % 10 != 0) {
System.out.println();
}
}
}
Um .. this isn't eloquent in the least but I tried to make the fewest changes to your existing code sample.
public class ArrayLoop {
public static void main(String args[]) {
double alpha[] = new double[50];
for (int i = 0; i < 25; i++) {
alpha[i] = i * i;
}
for (int i = 25; i < 50; i++) {
alpha[i] = 3 * i;
}
System.out.println("The values are: ");
for (int i = 0; i < 50; i++) {
System.out.print(alpha[i] + " ");
}
System.out.println();
System.out.println();
for (int i = 1; i < alpha.length; i++) {
if (i != 1 && i % 10 == 0) {
System.out.print(alpha[i - 1] + " ");
System.out.println();
} else {
System.out.print(alpha[i - 1] + " ");
}
}
System.out.print(alpha[49]);
}
}
Edit: A better condition would be ...
for (int i = 0; i < alpha.length; i++) {
if (i > 0 && i % 10 == 9) {
System.out.print(alpha[i] + " ");
System.out.println();
} else {
System.out.print(alpha[i] + " ");
}
}
You have to print the number first then decide whether to print space or newline by checking the modulus:
int arr[] = new int[50];
// Initialize array here
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]);
if (i > 0 && (i + 1) % 10 == 0) {
System.out.println();
} else {
System.out.print(" ");
}
}
You have a couple of % 10 snippets in your code so I'm not entirely certain how that's "trying something without modulus" :-)
Having said that, modulus is exactly what you need, as per the following psuedo-code:
count = 0
for each item in list:
if count > 0 and (count % 10) == 0:
print end of line
print item
print end of line
In Java, you would use something like:
public class Test {
static public void main(String args[]) {
for (int i = 0; i < 24; i++) {
if ((i > 0) &&((i % 10) == 0)) {
System.out.println();
}
System.out.print ("" + i * 3 + " ");
}
System.out.println();
}
}
In other words, immediately before you print an item, check to see if it should be on the next line and, if so, output a newline before printing it.
Note that arrays in Java are zero based, so you need to start with an index of zero rather than one in your loops.
Now that's pretty close to what you have so you're on the right track but, for the life of me, I cannot see in your print() method where you actually print the item! That should be number one on your list of things to look into :-)
I urge you to try and work it out from the above text and samples but, if you're still having troubles after more than half an hour or so, the below code shows how I'd do it.
public class Test {
static void print (double m_array[]) {
for (int i = 0; i < m_array.length; i++) {
if ((i > 0) && ((i % 10) == 0))
System.out.println();
System.out.print (m_array[i] + " ");
}
System.out.println();
}
static public void main(String args[]) {
double[] x = new double[15];
for (int i = 0; i < x.length; i++)
x[i] = i * 3;
print (x);
}
}