Java: Calculate for loop - java

I've now googled around and tried various methods myself without any success.
So to the problem,
I've got this loop, I type in a number "n" ex. 10. Then the program counts from 1 to 10.
This is the loop I'm using.
n = Keyboard.readInt();
for(int e = 1; e <=n; e++)
System.out.println(e);
That works fine, but now I want to calculate the numbers that has been shown in loop so..It would be 1+2+3+4+5+6+7+8+9+10 (If 'n' was chosen as number 10) and it should give the calculation of that so it would say 1+2+3+4+5+6+7+8+9+10 = 55.
Would be great if anyone here could help me.
Thanks in advance,
Michael.

You could do it the hard way or the easy way:
The hard way: Keep a running sum and add to it inside the loop.
The easy way: Notice that the sum you're looking for equals n*(n+1)/2 (which is easy to prove).

StringBuilder buffer = new StringBuilder();
int n = Keyboard.readInt();
int sum = 0;
for ( int e = 1; e <=n; e++ )
{
buffer.append( "+ " + e );
sum += e;
}
System.out.println( buffer.substring( 2 ) + " = " + sum );

Do it like that:
public static void main(String[] args) {
int n = 10;
int sum = 0;
for(int e = 1; e <=n; e++)
sum = sum + e;
System.out.println(sum);
}

int sum = 0;
for(int e = 1; e <=n; e++)
{
sum += e;
}
System.out.println(sum);

Use another variable to accumulate the results.

I feel like spoon-feeding, so here's the code:
public static void main(String args[]) {
int n = Keyboard.readInt();
int total = 0;
for (int i = 1; i <= n; i++)
total += i;
System.out.println(total);
}

Try this:
n = Keyboard.readInt();
int total = 0;
StringBuilder arith = new StringBuilder();
for(int e = 1; e <=n; e++) {
total += e;
arith.append(e + (e < n? "+" : ""));
}
arith.append("=" + total);
System.out.println(arith.toString());

Related

Out of Memory Heap Space

I am working on a code that will output all the possible combinations of a certain amount of objects that will occur between three possibilities. My code is working for smaller numbers like 10,000 but I want it to be able to go up to 100,000. Anytime I go above 10,000 I get the following error code: java.lang.OutOfMemoryError: Java heap space.
Is there a more efficient way to store this information, or be able to circumvent the error code somehow? I have the code below to show what I am talking about
public static double Oxygen[][];
public static int OxygenPermutationRows;
public void OxygenCalculations(){
Scanner reader = new Scanner(System.in);
System.out.print("Oxygen Number: ");
int oxygenNumber = reader.nextInt();
System.out.println();
int oxygenIsotopes = 3;
OxygenPermutationRows = 0;
//Number of Feesable Permutations
if(oxygenNumber % 2 == 0)
{
OxygenPermutationRows = (1 + oxygenNumber) * ((oxygenNumber / 2) + 1);
}
else
{
OxygenPermutationRows = (1 + oxygenNumber) * (int)Math.floor(oxygenNumber / 2) + (int)Math.ceil(oxygenNumber / 2) + 2 + oxygenNumber;
}
int [][] Permutations = new int[OxygenPermutationRows][oxygenIsotopes];
int counterrow = 0;
int k;
for (int f = 0; f <= oxygenNumber; f++)
{
for (int j = 0; j <= oxygenNumber; j++)
{
k = oxygenNumber - j - f;
Permutations[counterrow][0] = f;
Permutations[counterrow][1] = j;
Permutations[counterrow][2] = k;
counterrow++;
if(f+j == oxygenNumber)
{
j = oxygenNumber + 10;
}
}
}
//TO CHECK PERMUTATION ARRAY VALUES
System.out.println("PERMUTATION ARRAY =======================================");
for (int i = 0; i < OxygenPermutationRows; i++) {
System.out.println();
for (int j = 0; j < 3; j++) {
System.out.print(Permutations[i][j] + " ");
}
}
public double[][] returnOxygen()
{
return Oxygen;
}
public double returnOxygenRows()
{
return OxygenPermutationRows;
}
}
Couldn't you split the 100000 iterations in chunks? Maybe chunks of 10000 iterations? And for every chunk, write the result in a file.This will get rid of the OOM error.
Raise max memory with the parameter -Xmx, you can do this in the run configuration for the java class

Calculate factorial of 50 using array only in java

I'm a total beginner of java.
I have a homework to write a complete program that calculates the factorial of 50 using array.
I can't use any method like biginteger.
I can only use array because my professor wants us to understand the logic behind, I guess...
However, he didn't really teach us the detail of array, so I'm really confused here.
Basically, I'm trying to divide the big number and put it into array slot. So if the first array gets 235, I can divide it and extract the number and put it into one array slot. Then, put the remain next array slot. And repeat the process until I get the result (which is factorial of 50, and it's a huge number..)
I tried to understand what's the logic behind, but I really can't figure it out.. So far I have this on my mind.
import java.util.Scanner;
class Factorial
{
public static void main(String[] args)
{
int n;
Scanner kb = new Scanner(System.in);
System.out.println("Enter n");
n = kb.nextInt();
System.out.println(n +"! = " + fact(n));
}
public static int fact(int n)
{
int product = 1;
int[] a = new int[100];
a[0] = 1;
for (int j = 2; j < a.length; j++)
{
for(; n >= 1; n--)
{
product = product * n;
a[j-1] = n;
a[j] = a[j]/10;
a[j+1] = a[j]%10;
}
}
return product;
}
}
But it doesn't show me the factorial of 50.
it shows me 0 as the result, so apparently, it's not working.
I'm trying to use one method (fact()), but I'm not sure that's the right way to do.
My professor mentioned about using operator / and % to assign the number to the next slot of array repeatedly.
So I'm trying to use that for this homework.
Does anyone have an idea for this homework?
Please help me!
And sorry for the confusing instruction... I'm confused also, so please forgive me.
FYI: factorial of 50 is 30414093201713378043612608166064768844377641568960512000000000000
Try this.
static int[] fact(int n) {
int[] r = new int[100];
r[0] = 1;
for (int i = 1; i <= n; ++i) {
int carry = 0;
for (int j = 0; j < r.length; ++j) {
int x = r[j] * i + carry;
r[j] = x % 10;
carry = x / 10;
}
}
return r;
}
and
int[] result = fact(50);
int i = result.length - 1;
while (i > 0 && result[i] == 0)
--i;
while (i >= 0)
System.out.print(result[i--]);
System.out.println();
// -> 30414093201713378043612608166064768844377641568960512000000000000
Her's my result:
50 factorial - 30414093201713378043612608166064768844377641568960512000000000000
And here's the code. I hard coded an array of 100 digits. When printing, I skip the leading zeroes.
public class FactorialArray {
public static void main(String[] args) {
int n = 50;
System.out.print(n + " factorial - ");
int[] result = factorial(n);
boolean firstDigit = false;
for (int digit : result) {
if (digit > 0) {
firstDigit = true;
}
if (firstDigit) {
System.out.print(digit);
}
}
System.out.println();
}
private static int[] factorial(int n) {
int[] r = new int[100];
r[r.length - 1] = 1;
for (int i = 1; i <= n; i++) {
int carry = 0;
for (int j = r.length - 1; j >= 0; j--) {
int x = r[j] * i + carry;
r[j] = x % 10;
carry = x / 10;
}
}
return r;
}
}
How about:
public static BigInteger p(int numOfAllPerson) {
if (numOfAllPerson < 0) {
throw new IllegalArgumentException();
}
if (numOfAllPerson == 0) {
return BigInteger.ONE;
}
BigInteger retBigInt = BigInteger.ONE;
for (; numOfAllPerson > 0; numOfAllPerson--) {
retBigInt = retBigInt.multiply(BigInteger.valueOf(numOfAllPerson));
}
return retBigInt;
}
Please recall basic level of math how multiplication works?
2344
X 34
= (2344*4)*10^0 + (2344*3)*10^1 = ans
2344
X334
= (2344*4)*10^0 + (2344*3)*10^1 + (2344*3)*10^2= ans
So for m digits X n digits you need n list of string array.
Each time you multiply each digits with m. and store it.
After each step you will append 0,1,2,n-1 trailing zero(s) to that string.
Finally, sum all of n listed string. You know how to do that.
So up to this you know m*n
now it is very easy to compute 1*..........*49*50.
how about:
int[] arrayOfFifty = new int[50];
//populate the array with 1 to 50
for(int i = 1; i < 51; i++){
arrayOfFifty[i-1] = i;
}
//perform the factorial
long result = 1;
for(int i = 0; i < arrayOfFifty.length; i++){
result = arrayOfFifty[i] * result;
}
Did not test this. No idea how big the number is and if it would cause error due to the size of the number.
Updated. arrays use ".length" to measure the size.
I now updated result to long data type and it returns the following - which is obviously incorrect. This is a massive number and I'm not sure what your professor is trying to get at.
-3258495067890909184

How do I return a value from within a for loop?

Here's my code:
import java.util.*;
public class factorialdisplay {
// Main Method. Prints out results of methods below.
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
// Asks user for input
System.out.println("Please enter a number: ");
int n = console.nextInt();
for (int i = 0; i <= n; ++i) {
System.out.println(i + "! = " + factorial(n));
}
}
public static int factorial (int n) {
int f = 1;
for (int i = 1; i <= n; ++i) {
f *= i;
return f;
}
return f;
}
}
I'm trying to get the output:
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
But when I run the code, I get this:
0! = 1
1! = 1
2! = 1
3! = 1
4! = 1
5! = 1
My question is, how would I return the result of each iteration of a for loop, through the factorial static method, to the main method?
You need to remove the return f; statement which is there in the for loop. The return within the if will always return to the calling method immediately after the first iteration. And that is why you're getting 1 as the result for all the factorials.
public static int factorial (int n) {
int f = 1;
for (int i = 1; i <= n; ++i) {
f *= i;
// return f; // Not needed - this is causing the problem
}
return f; // This is your required return
}
And as Ravi pointed out
for (int i = 1; i <= n; ++i) { // well 0 will return 1 as well, so no prob unless you don't need 0 factorial
System.out.println(i + "! = " + factorial(i)); // you need to pass i instead of n as i is the counter here
}
Don't return here:
for (int i = 1; i <= n; ++i) {
f *= i;
return f; // here!
}
but rather at the end of your loop. You need to accumulate your final result over all iterations of your loop.
Three problems with the code:
Start at i = 1
Call factorial(i) not factorial(n)
for (int i = 1; i <= n; ++i) { // (1) start at i = 1
System.out.println(i + "! = " + factorial(i)); // (2) pass i not n
}
Return once; after the loop ends
for (int i = 1; i <= n; ++i) {
f *= i;
// return f; // (3) don't return from here
}
return f;
Hmmm... you sort of think of a yield operation (which is available in some languages, but not Java). yield is a construct which says: "return a value from the function, but bookmark the place where I currently am and let me come back to it later". return on the other hand says something like "return the value and discard everything I do". In Java, you can't "put a loop on hold" and come back to it later.
I undestand that what you are trying to achieve is not wasting time by repeating calculations (and just leaving the return which has been proposed in other answers is incredibly bad for performance; justr try it for some bigger numbers...). You could achieve it by not yielding the results, but storing them in an array. Like this:
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
// Asks user for input
System.out.println("Please enter a number: ");
int n = console.nextInt();
int[] results = factorials(n);
for (int i = 0; i <= n; ++i) {
System.out.println(i + "! = " + results[i]);
}
and the function:
public static int[] factorials (int n) {
int[] results = new int[n + 1];
results[0] = 1;
int f = 1;
for (int i = 1; i <= n; ++i) {
f *= i;
results[i] = f;
}
return results;
}
Note that the above could be written better - I tried to modify your code as little as possible.

Nested For Loops Dynamic Depth Java

Hello I'm new to programming and registered to this forum :)
So I created a little program with nested for loops that prints out all combinations of five numbers which can have a value from 0 to 5. With nested for-loops this works fine. But isn't there a cleaner solution? I tried it with calling the for loop itself, but my brain doesn't get the solution.. :(
//my ugly solution
int store1, store2, store3, store4, store5;
for (int count = 0; count <= 5; count++) {
store1 = count;
for (int count2 = 0; count2 <= 5; count2++) {
store2 = count2;
for (int count3 = 0; count3 <= 5; count3++) {
store3 = count3;
for (int count4 = 0; count4 <= 5; count4++) {
store4 = count4;
System.out
.println(store1 + " " + store2 + " " + store4);
}
//I'm trying around with something like this
void method1() {
for (int count = 0; count <= 5; count++) {
list.get(0).value = count;
count++;
method2();
}
}
void method2() {
for (int count = 0; count <= 5; count++) {
list.get(1).value = count;
count++;
method1();
}
}
Usually when people try to use recursion or functional, using a loop is simpler or faster. However, in this case recursion is the simpler option in combination with a loop.
public static void method(List<Integer> list, int n, int m) {
if (n < 0) {
process(list);
} else {
for(int i = 0; i < m; i++) {
list.set(n, i);
method(list, n-1, m);
}
}
}
I know that you are trying combinations but this might help.
Permutation with repetitions
When you have n things to choose from ... you have n choices each time!
When choosing r of them, the permutations are:
n × n × ... (r times) = n^r
//when n and r are known statically
class Permutation
{
public static void main(String[] args)
{
char[] values = {'a', 'b', 'c', 'd'};
int n = values.length;
int r = 2;
int i = 0, j = 0;
for(i=0; i<n; i++)
{
for(j=0; j<n; j++)
{
System.out.println(values[j] + " " + values[i]);
}
}
}
}
//when n and r are known only dynamically
class Permutation
{
public static void main(String[] args)
{
char[] values = {'a', 'b', 'c', 'd'};
int n = values.length;
int r = 2;
int i[] = new int[r];
int rc = 0;
for(int j=0; j<Math.pow(n,r); j++)
{
rc=0;
while(rc<r)
{
System.out.print(values[i[rc]] + " ");
rc++;
}
System.out.println();
rc = 0;
while(rc<r)
{
if(i[rc]<n-1)
{
i[rc]++;
break;
}
else
{
i[rc]=0;
}
rc++;
}
}
}
}
Something like this?
// Print all sequences of len(list)+n numbers that start w/ the sequence in list
void method( list, n ) {
if ( list.length == n )
// print list
else for ( int c=0; c<=5; c++ ) {
// add c to end of list
method( list, n );
// remove c from end of list
}
}
Initial call would be method( list, 5 ) where list is initially empty.
here another interative but less elegant version
while (store1 < 6) {
store5++;
if (store5 == 6) {
store5 = 0;
store4++;
}
if (store4 == 6) {
store4 = 0;
store3++;
}
if (store3 == 6) {
store3 = 0;
store2++;
}
if (store2 == 6) {
store2 = 0;
store1++;
}
System.out.println(store1 + " " + store2 + " " + store3 + " " + store4 + " " + store5 + " ");
}
The simplest code I can think of would tackle the problem with an entirely different approach:
public class TestA {
public static void main(String[] argv) {
for (int i=0; i<(6 * 6 * 6 * 6 * 6); ++i) {
String permutation = Integer.toString(i, 6);
System.out.println("00000".substring(permutation.length()) + permutation);
}
}
}
From your text (not your code) I gather you have 5 places and 6 symbols, which suggests there are 6 to the 5th power combinations. So the code just counts through those numbers and translates the number to the output combination.
Since this can also be viewed as a number system with base 6, it makes use of Integer.toString which already has formatting code (except the leading zeros) for this. Leading zeros are added where missing.

from loop to Nested loops?

I have this program that returns a factorial of N. For example, when entering 4,,, it will give 1! , 2! , 3!
How could I convert this to use nested loops?
public class OneForLoop
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter a number : ");
int N = input.nextInt();
int factorial = 1;
for(int i = 1; i < N; i++)
{
factorial *= i;
System.out.println(i + "! = " + factorial);
}
}
}
If written as nested loops it would look like this:
for (int i = 1; i < N; ++i)
{
int factorial = 1;
for (int j = 1; j <= i; ++j) {
factorial *= j;
}
System.out.println(i + "! = " + factorial);
}
Result:
Enter a number : 10
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
This program gives the same result as yours, it just takes longer to do so. What you have already is fine. Note also that the factorial function grows very quickly so an int will be too small to hold the result for even moderately large N.
If you want to include 10! in the result you need to change the condition for i < N to i <= N.
Right now you are calculating your factorial incrementally. Just recalculate it from scratch every time. Be advised that what you have now is better than what I'm posting, but this does follow your requirements.
public class TwoForLoops
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter a number : ");
int N = input.nextInt();
int factorial = 1;
for (int i = 1; i < N; ++i)
{
factorial = 1;
for(int j = 1; j <= i; j++)
{
factorial *= j;
}
System.out.println(i + "! = " + factorial);
}
}
}
Rather than just computing everything in a linear fashion, you could consider an inner loop which would do something like what you have in the outer loop. Is that what you are trying to achieve?
Would you consider recursion a nested loop?
public long factorial(int n)
{
if (n <= 1)
return 1;
else
return n * factorial(n - 1);
}
public static void main(String [] args)
{
//print factorials of numbers 1 to 10
for(int i = 1; i <= 10; i++)
System.out.println(factorial(i));
}

Categories