Sum of factorials in Java [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I made a program to sum factorials in java like 4! + 3! + 2! + 1! = 33, but it doesn't work. Could anyone help explain why?
import javax.swing.JOptionPane;
public class fac {
public static void main(String[] args) {
int sum = 0, fact, i, j;
fact = Integer.parseInt(JOptionPane.showInputDialog("ENTER NO"));
for (i = fact; i > 1; i--) {
for (j = fact - 1; j > 0; j--)
fact = fact * j;
sum = sum + fact;
}
sum = sum + 1;
System.out.print("SUM OF FACTORIAL = "+sum);
}
}

You are repeatingly calculating factorial of fact in the outer loop. The start value of the inner loop is wrong.
But you should have found this error by yourself using a debugger.

This is where methods might come in handy. First an outer loop because you're counting down (from 4, in this example).
static final int NR = 4; //for example
static void main(String[] args) {
int total = 0;
for (int i = NR; i > 0; i--)
total += calculateFactorial(i); //i += j; is the same as i = i + j;
System.out.println("Answer: " + total);
}
Now it looks way easier, right? The code suddenly became readable. Now for calculateFactorial(int nr) all we have to do is calculate 4 * 3 * 2 * 1 (for the factorial of 4, that is):
public static int calculateFactorial(int nr) {
int factorialTotal = 1;
for (int i = nr; i > 0; i--)
factorialTotal *= i; //i *= j; is the same as i = i * j;
return factorialTotal;
}
Methods just made code easy to read and write. I'd suggest you read a book like Clean Code

Related

Review problem - 1 ArrayList module Solving problem with java(Codechef) [closed]

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 8 days ago.
Improve this question
Link of problem
Code
import java.util.*;
class Codechef {
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
int t = read.nextInt();
for (int i = 0; i < t; i++) {
ArrayList < Integer > a = new ArrayList < Integer > ();
int n = read.nextInt();
for (int j = 1; j <= n; j++) {
int ele = read.nextInt();
a.add(ele);
}
int k = 0, count = 1;
while (k < n - 1) {
if (a.get(k) != a.get(k + 1)) {
count++;
}
k++;
}
System.out.println(count);
}
}
}
Input
4
1
5
2
1 1
3
1 2 3
4
2 1 2 2
Expected Output
1
1
3
3
My output - It is giving runtime error in the output.`

I do not understand this part. Can anyone explain how this loop and math.random*2 is working [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last year.
Improve this question
help me to understand this code
public class Exercise12 {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Input a number: ");
int n = in.nextInt();
printMatrix(n);
}
public static void printMatrix(int n) {
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
System.out.printin((int)(Math.random() * 2) + " ");
}
System.out.println();
}
}
}
Math.random() returns a number between 0.0 (inclusive) and 1.0 (exclusive).
Therefore (Math.random() * 2) is a number between 0.0 (inclusive) and 2.0 (exclusive).
Therefore (int)(Math.random() * 2) is either 0 or 1:
If (Math.random() * 2) == 0.xxxx, casting it to int results in 0
If (Math.random() * 2) == 1.xxxx, casting it to int results in 1
Hence this code prints a matrix of n * n 0 or 1 elements.

Java Math random() to print only one number [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
How could i get this code to just give me ONE number between 0-9.
At the moment it prints 10 numbers between that 0-9 but i need it to just pick one number from 0-9
import java.lang.Math;
public class random {
public static void main(String args[]) {
int max = 9;
int min = 0;
int range = max - min + 1;
for (int i = 0; i < 9; i++) {
int rand = (int)(Math.random() * range) + min;
System.out.println(rand);
}
}
}
Your System.out.println(rand) is inside the for loop that repeats 9 times. If you want a single value to be displayed, just remove the loop. That should fix it. Like the following:
public class random {
public static void main(String args[]) {
int max = 9;
int min = 0;
int range = max - min + 1;
int rand = (int)(Math.random() * range) + min;
System.out.println(rand);
}
}

I am working with fibonacci numbers, where the "n" for the n-th number is in 5-6 digits. how can i reduce the time taken for execution? [closed]

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 2 years ago.
Improve this question
In this specific problem, what I had to do is find the Fibonacci numbers, square them, and then find the sum of those squared numbers. Which was fine up until the range limit of the long data type.
Here's what I've got till now... I switched to BigInteger after noticing that the range of long couldn't handle the large Fibonacci numbers, and that did the trick but increased the time complexity exponentially. And since I needed to retain most of the numbers, I needed to make an array for the numbers to store them.
import java.util.*;
import java.math.*;
public class FibonacciSumSquares {
private static BigInteger getFibonacciSumSquares(int n) {
if (n <= 1)
return BigInteger.valueOf(n);
BigInteger sum = BigInteger.valueOf(0);
BigInteger a[] = new BigInteger[n];
a[0] = a[1] = BigInteger.ONE;
for (int i = 2; i < n; i++) {
a[i] = a[i - 1].add(a[i - 2]);
a[i] = a[i].pow(2);
sum = sum.add(a[i]);
}
return sum;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
System.out.println(getFibonacciSumSquares(n));
}
}
After accepting the first answer I ran some stress tests on the code snippet and the correction that was needed was an "=" sign in the code. hope that helps. For more details please refer to the answer's comments.
BigInteger runs more slower than java primitive types, so use primitive in long range.
here is my code and result:
public class FibonacciSumSquares {
private static BigInteger getFibonacciSumSquares(int n) {
if (n <= 1)
return BigInteger.valueOf(n);
BigInteger sum = BigInteger.ZERO;
long last = 1, lastTwo = 1, current = 0;
BigInteger lastBigInteger = BigInteger.ONE;
BigInteger lastTwoBigInteger = BigInteger.ONE;
BigInteger currentBigInteger;
boolean isUsePrimary = true;
for (int i = 2; i <= n; i++) {
if (isUsePrimary) {
current = last + lastTwo;
current = current * current;
if (current > (last + lastTwo)) {
lastTwo = last;
last = current;
sum = sum.add(BigInteger.valueOf(current));
} else {
isUsePrimary = false;
lastTwoBigInteger = BigInteger.valueOf(lastTwo);
lastBigInteger = BigInteger.valueOf(last);
currentBigInteger = lastBigInteger.add(lastTwoBigInteger);
currentBigInteger = currentBigInteger.pow(2);
sum = sum.add(currentBigInteger);
}
} else {
currentBigInteger = lastBigInteger.add(lastTwoBigInteger);
currentBigInteger = currentBigInteger.pow(2);
sum = sum.add(currentBigInteger);
}
}
return sum;
}
public static void main(String[] args) {
long start = System.currentTimeMillis();
System.out.println(getFibonacciSumSquares(10000));
System.out.println("used time(ms): " + (System.currentTimeMillis() - start));
/**
* On: MacBook Pro (Retina, 15-inch, Mid 2014)
*
* n = 10000
* 811453295998950457153326378602357232029212
* used time(ms): 24
*
* n = 20000
* 1623556274380606238932066737816445867589212
* used time(ms): 32
*
* n = 999999
* 81209566945485034687670444066761210743605656
* used time(ms): 368
*/
}
}

Divide an int into whole numbers [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am looking for a way to divide an int into whole numbers.
What I mean by this: if I have a number 30 and I want to divide this by 4, I want the output to be 8,8,7,7.
Is there a way in Java to do this?
Thanks in advance.
Sure, Java is turing complete and therefore allows you to implement any algorithm.
I assume that the difference between the resulting numbers should be at most one - you did not explicitly write this.
Try this:
final int input = 30;
final int numberOfPieces = 4;
final int quotient = input / numberOfPieces;
final int remainder = input % numberOfPieces;
int [] results = new int[numberOfPieces];
for( int i = 0; i < numberOfPieces; i++ ) {
results[i] = i < remainder ? quotient + 1 : quotient;
}
This code first calculates the integer quotient and then equally distributes the remainder to the first "pieces".
Since you don't want equal splits of the number, what you may do is :
Divide the number by how many ever parts you want.
Round() the result
Add up the rounded of number how many ever times required & check if sum is same, if not add or subtract 1 as necessary.
Eg: N = 150 , parts = 4
=> 37.5 , Round it round(37.5) => 38
Now, 38*4 = 152 and 152-150 = 2 so subtract 2 from a number and your answer is 38, 38, 38 & 36.
Code:
import java.util.*;
import java.lang.*;
import java.io.*;
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
float number = 30.0f;
float parts = 4.0f;
float val = number / parts;
val = Math.round(val);
if (val * parts == number){
System.out.println("Numbers are:");
for (int i = 0; i < parts; i++)
System.out.println(val);
}
else {
int diff = Math.round((val * parts) - number);
System.out.println("Numbers are:");
for(int i = 0;i < parts - 1; i++)
System.out.println(val);
System.out.println(val - diff);
}
}
}
Output:
Numbers are:
8.0
8.0
8.0
6.0
If you want to equally share the difference in the above case then just replace the else part with this:
else {
int diff = Math.round((val * parts) - number);
System.out.println("Numbers are:");
for (int i = 0; i < parts - diff; i++)
System.out.println(val);
for (int i = 0; i < diff; i++)
System.out.println(val - 1);
}
Your output will be:
Numbers are:
8.0
8.0
7.0
7.0

Categories