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));
}
Related
I seriously need help please
1=1, 1+2=3, 1+2+3=6, 1+2+3+4=10
I don't know how to code the equation part
import java.util.Scanner;
public class Equations {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println ("Enter a number between 1 to 15: ");
int num = scan.nextInt();
int total = 0;
int save;
for(int i=1;i<=num;i++)
{
for(int j=1;j<=num;j++)
{
save = total+i;
i++;
}
System.out.print (save+"="+total);
System.out.println ();
}
}
This is all I have, and it doesn't work.
There are quite a few things off. You're not resetting total or save after each equation. save is an int, so it can't hold the equation string. j needs to increment to i, not num. total is never incremented. i++ doesn't belong in the inner loop.
Here's a simple, correct version:
for (int i = 1; i <= num; i++) {
int sum = 0;
String equation = "";
for (int j = 1; j <= i; j++) {
sum += j;
equation += "+" + j;
}
System.out.println(equation.substring(1) + "=" + sum);
}
This program is meant to display an array and compute prime numbers between 1 and whatever the user enters. On some IDEs that "Capture Output", the list of prime numbers will not "word-wrap". Instead, it will display one VERY long line of numbers. This can be handled by inserting a "line-feed" in the display code that is activated every 15 numbers. I have no clue how to do this, my code is below.
import java.util.Scanner;
import java.text.DecimalFormat;
public class Lab11avst {
public static void main(String[] args) {
// This main method needs additions for the 100 point version.
Scanner input = new Scanner(System.in);
System.out.print("Enter the primes upper bound ====>> ");
final int MAX = input.nextInt();
boolean primes[];
primes = new boolean[MAX];
computePrimes(primes);
displayPrimes(primes);
}
public static void computePrimes(boolean primes[]) {
System.out.println("\nCOMPUTING PRIME NUMBERS");
int newLine = 15;
int multiplicator = 1;
int list[] = new int[1000];
for (int k=2; k < primes.length; k++) {
primes[k] = true;
}
for (int k=2; k < primes.length; k++)
for (int x=2*k;x<primes.length;x+=k)
primes[x] = false;
}
public static void displayPrimes(boolean primes[]) {
DecimalFormat output = new DecimalFormat("0000");
System.out.println("\n\nPRIMES BETWEEN 1 AND " + primes.length);
int numPrimes = 0;
for (int k=2; k < primes.length; k++) {
if (numPrimes % 15 == 0) System.out.println("");
if (primes[k]) System.out.print(output.format(k) + " ");
++numPrimes;
}
}
}
If you have to proceed with your current method of computing prime numbers, then you can just keep track of how many primes have been printed, and add a line break for every 15 numbers. I suggest making a slight change to your displayPrimes() method:
public static void displayPrimes(boolean primes[]) {
DecimalFormat output = new DecimalFormat("0000");
System.out.println("\n\nPRIMES BETWEEN 1 AND " + primes.length);
int numPrimes = 0;
for (int k = 2; k < primes.length; k++) {
if (numPrimes % 15 == 0) System.out.println("");
if (primes[k]) System.out.print(output.format(k) + " ");
++numPrimes;
}
}
I use System.out.println here, which guarantees that the correct line break will be used for any platform.
However, a nicer way to approach the entire problem would be to just compute the actual prime numbers themselves, and then just iterate that array and display. Using this approach would require a complete refactor of code, maybe not what you want, and also probably too broad for a single question.
Let numPrimes indeed count the printed primes:
int numPrimes = 0;
for (int k = 2; k < primes.length; k++) {
if (primes[k]) {
if (numPrimes % 15 == 0) {
System.out.println();
}
System.out.print(output.format(k) + " ");
++numPrimes;
}
}
And \n is on Unix/Linux and MacOS, Windows uses \r\n:
System.out.println("\nCOMPUTING PRIME NUMBERS");
should be
System.out.println();
System.out.println("COMPUTING PRIME NUMBERS");
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
I was practicing with some exercises from UVA Online Judge, I tried to do the Odd sum which basically is given a range[a,b], calcule the sum of all odd numbers from a to b.
I wrote the code but for some reason I don't understand I'm getting 891896832 as result when the range is [1,2] and based on the algorithm it should be 1, isn't it?
import java.util.Scanner;
public class OddSum
{
static Scanner teclado = new Scanner(System.in);
public static void main(String[] args)
{
int T = teclado.nextInt();
int[] array = new int[T];
for(int i = 0; i < array.length; i++)
{
System.out.println("Case "+(i+1)+": "+sum());
}
}
public static int sum()
{
int a=teclado.nextInt();
int b = teclado.nextInt();
int array[] = new int[1000000];
for (int i = 0; i < array.length; i++)
{
if(a%2!=0)
{
array[i]=a;
if(array[i]==(b))
{
break;
}
}
a++;
}
int res=0;
for (int i = 0; i < array.length; i++)
{
if(array[i]==1 && array[2]==0)
{
return 1;
}
else
{
res = res + array[i];
}
}
return res;
}
}
Your stopping condition is only ever checked when your interval's high end is odd.
Move
if (array[i] == (b)) {
break;
}
out of the if(a % 2 != 0) clause.
In general, I don't think you need an array, just sum the odd values in your loop instead of adding them to the array.
Keep it as simple as possible by simply keeping track of the sum along the way, as opposed to storing anything in an array. Use a for-loop and add the index to the sum if the index is an odd number:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter minimum range value: ");
int min = keyboard.nextInt();
System.out.println("Enter maximum range value: ");
int max = keyboard.nextInt();
int sum = 0;
for(int i = min; i < max; i++) {
if(i % 2 != 0) {
sum += i;
}
}
System.out.println("The sum of the odd numbers from " + min + " to " + max + " are " + sum);
}
I don't have Java installed right now, however a simple C# equivalent is as follows: (assign any values in a and b)
int a = 0;
int b = 10;
int result = 0;
for (int counter = a; counter <= b; counter++)
{
if ((counter % 2) != 0) // is odd
{
result += counter;
}
}
System.out.println("Sum: " + result);
No major dramas, simple n clean.
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.