java: how to calculate multiplication between all values in variable difference - java

I received that task:
"A small method, calculateProduct is to be written. It will ask the user to enter two int values, and then calculate and display the product of all the values between the two values entered. For example if the user enters the numbers 2 and 5 the program will display the result 120 (calculated as 2 * 3 * 4 * 5)"
I tried to build something like this:
import java.util.Scanner;
public class Exam {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int a;
int b;
int big;
int small;
//ask to insert two variables
System.out.println("Insert variable a");
a = in.nextInt();
System.out.println ("Insert variable b");
b=in.nextInt();
// compare two variables
// set the biggest variables to b, the smallest - to a
if (a >=b){
big=a;
small=b;
}
else {
big=b;
small=a;
}
// set the do while loop to complete the code. Run multiplying before counter won't fit to b variable
int result = small;
for (int i=small; i<=big;i++){
result*=i;
}
System.out.println("the multiplication progression between "+small+" and "+big+" equals to "+result);
}
}
However, when I insert 2 and 5 the result is 240. Does anybody know how to fix it? thanks!

Change loop to:
for (int i = small + 1; i <= big; i++)
{
result *= i;
}

you init result with small then multiply it by small again.
Fix: Start the for statement with small+1
...
int result = small;
for (int i=small+1; i<=big;i++){
result*=i;
}
....

The other obvious solution here is to change the init statement from
int result = small;
to
int result = 1;
In that case you don't have to touch your looping code.
And for the record: "small" is a rather bad name here, why not call it "smallerInput" or something like that.
Finally: you could avoid dealing with "small" - if a < b you can simply loop from a to b; and otherwise you could loop "backwards" from "b to a".

Just change your for loop as below mentioned will solve your problem.
The problem in your loop is :
In its first iteration it is multiple with itself rather than its
incremented value.
From:
for (int i=small; i<=big;i++)
To:
for (int i=small+1; i<=big;i++)

The task is to write a method called "calculateProduct". Above you are doing all your callculation in your main method. Try to separate that. Example :
import java.util.Scanner;
public class Exam {
public static void main (String[]args) {
Scanner in = new Scanner(System.in);
int a;
int b;
System.out.println("Insert variable a");
a = in.nextInt();
System.out.println ("Insert variable b");
b=in.nextInt();
if(a>=b){
calculateProduct(b,a);
}
else{
calculateProduct(a,b);
}
}
public static void calculateProduct (int m, int n) {
int result = 1;
for (int i = m; i <= n; i++) {
result *= i;
}
System.out.println("the multiplication progression between "+m+" and "+n+" equals to "+result);
}
}

Related

Calculating a series

I am trying to write a program that accepts an integer from the user, then it should calculate this series S = 1/2! - 1/3! + 1/4! – 1/5! + .... all the way to 1/x! where x is the integer taken from the user, I already wrote this code to calculate the factorial of x :
import java.util.Scanner;
public class Factorial {
public static void main(String args[]){
Scanner x = new Scanner(System.in);
System.out.println("Enter a number: ");
int number = x.nextInt();
int fact = 1;
for (int i = 1; i <= number; i++){
fact = fact*i;
}
System.out.println("The factorial of "+number+" is "+fact);
x.close();
}
}
but still am not sure how to code the series, any tips would be really appreciated.
Also I am sorry if my code is not organized I don't know how to use stackoverflow tools ;( .
Ideally, what you want is to separate your code into multiple functions, and think logically.
Since you said you didn't want tips, I'll just try to put you on the right track.
Tip 1:
Separate your code into multiple functions
eg.
public static int factorial(int n){
int fact = 1;
for (int i = 1; i <= n; i++){
fact = fact*i;
}
return fact;
}
This allows you to split your code up into manageable chunks. Call each chunk at the appropriate time. This makes your code easier to read and more reusable
Tip 2:
One main class and the other class with functions.
Ideally, you want to create two classes, one which takes input from the user and one which contains all the functions you need. The main class taking the input will create an Object of the other class
public class Factorial{
public static void main(String args[]){
Scanner x = new Scanner(System.in);
System.out.println("Enter a number: ");
int number = x.nextInt();
Series s=new Series(number);
s.print();
x.close();
}
And in Series.java
public class Series{
int output;
int input;
Series(int i){
input=i;
//..here you calculate output
}
public int factorial(int n){
//.... the code
}
public void print(){
System.out.println("The calculation of " + input + " is " + output);
}
}
Tip 3:
Make a nice simple function to calculate the output. Sum up all your factorials over time
for (int i = 2; i <= input; i++) {
//if its even
if(i%2==0)
output = output + 1.0 / factorial(i);
else
output = output - 1.0 / factorial(i);
}
Add the following to your constructor and you'll have a well built Java program
Tip 4:: These sums are going to be decimals, not integers so you need to replace all your ints with doubles
First, you have to compute a sum of terms. The standard pattern is like
double sum = 0;
for (int i = first; i <= last; i++) {
sum += term(i);
}
then remark that
the first term is term(2) = +1/2!
the second term is term(3) = -1/3! = -term(2)/3
the third term is +1/4! = -term(3)/4
etc.
So you'll notice that each term can be easily obtained from the previous one.
This leads to
double sum = 0;
double term = (some value);
for (int i = first; i <= last; i++) {
term = (some expression involving i and previous term);
sum += term;
}
Exercise left as, huh, an exercise ?

Smallest number with digits product of n

I need to find the smallest number which digit numbers product is equal to a given num.
import java.util.Scanner;
class timus_1014_2 {
public static void main(String[] args){
int[] arr = new int[10]; // eskan ban# chem imanum inchi a statik,
int prod = 1;
int j = 0;
Scanner in = new Scanner(System.in);
int n = in.nextInt();
for (int i = 2; i < 10; ++i){
if (n % i == 0) {
arr[j] = i;
j++;
}
}
prod = prod * arr[j];
System.out.print(prod);
}
}
Something is wrong with the logic, whats is the problem when I input 10 it should give 25 but it gives 0. Please give ideas of how to make a program find a number which digits product is a given num.
If I understood your problem correctly you need a number whose product of digits equals a number N. Since you asked for new algorithm , you can chck following code.
Logic:
Note : For number whose prime factors are less than 10
Get all factors from 9 -> 2
add to list
print in reverse or use stack instead of list
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter number");
int num = in.nextInt();
List<Integer> lst = new ArrayList<>();
for (int p = 9; p >= 2; p--) {
while (num % p == 0) {
num /= p;
lst.add(p);
}
}
String smallestNumber = "";
for (int i = lst.size() - 1; i >= 0; i--) {
smallestNumber = smallestNumber + lst.get(i);
}
System.out.println("Smallest number : " + smallestNumber);
}
}
Output :
Enter number
10
Smallest number : 25
Enter number
144
Smallest number : 289
Enter number
12
Smallest number : 26
I suggest you look at each error is fix it one by one. I also suggest you use an IDE which will show you the errors and you type and will help ensure you don't have an overwhelming number of errors and you can see if those error disappear based on your corrections.
BTW Often when you use an array for a short piece of code, it can often be eliminate as I suspect it can be removed in your case.
Static methods can not access non-static members of class.
In your case prod is member variable of class but not static. To fix the error , try to make prod as static.
private static int prod = 1;
I would prefer , to make it local variable if no other method is using it.
The problem here is you need to create an object of the particular class to call a particular method associated with it
import java.util.Scanner;
class DigPro {
static int[] arr = new int[10]; // eskan ban# chem imanum inchi a statik,
int prod = 1;
public static void main(String[] args){
Scanner in = new Scanner(System.in);
DigPro obj = new DigPro();
obj.prime(in.nextInt());
}
public void prime(int n){
for (int i = 1; i < 10; ++i){
for (int j = 0; j < 9; ++j) {
if (n % i == 0) {
arr[j] = i;
}
prod = prod * arr[j];
}
}
System.out.print(prod);
}
}
Here you need to create an object say obj of DigPro class and then call prime(int n) method with that object. Also your division is startint with zero which is changed to one
In above code you are increasing j after the assigning value to arr[j].You should do the following:-
prod = prod * arr[j-1];
Here it will multiply prod with last array updated. That is why you are getting zero. And for your another question find the smallest number which digit numbers product is equal to a given num has similar answer at this link.
Since this is actually a pretty interesting problem, I took the time to come up with a correct solution for all possible integer inputs.
import java.util.*;
public class Main{
public static void main(String[] args) {
System.out.println("Enter number:");
int number = new Scanner(System.in).nextInt();
Stack<String> factors = new Stack<>();
if(number==0){
factors.push("0");
}else if(number==1){
factors.push("1");
}else{
for(int f=9;f>1;f--){
while(number%f==0){
factors.push(Integer.toString(f));
number/=f;
}
}
}
if(number<0){
factors.push("-");
}
if(number>9){
System.out.println("This is impossible.");
}else{
System.out.println("Smallest Number:");
while(!factors.empty()) System.out.print(factors.pop());
}
}
}

java reverse a string of numbers

I need to be able to input a list of numbers the last being -1 and have it print the reverse(not including -1) and then find the average. I have to use a function for finding the reverse. Im stuck because it cannot resolve my average which means I cannot run the program to see if there are other problems.
import java.util.Scanner;
public class Reverse {
public static void inReverse (int a) {
int number;
int[] value;
for (a = number - 2; a >= 0; a--) {
System.out.print(value[a] + " ");
}
}
public static double findAverage (int p, double average) {
int number;
for (p = number - 2; p >= 0; p--) {
average += value[p];
}
average = average / (number - 1);
return average;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] value;
int i, number, size;
size = 20;
System.out.println("Please enter the integers: ");
while (value[i - 1] != -1 && number < size) {
value[i] = input.nextInt();
i += 1;
number = i;
}
System.out.println("The values in reverse order are: ");
inReverse(i);
System.out.println(" ");
System.out.println("The average is " + average);
}
}
Your problem is that you have confused "local variables" with "fields".
Local variables are variables that you declare inside the body of a method. They can't be used before the declaration, and they can't be used once the method stops running - their values have ceased to exist.
Fields are variables that you declare inside your class, but outside any methods. These live inside each object of the class (or inside the class itself if you declare them as static), which means they keep their values from one method call to the next.
You have int number; and int[] value; declared inside different methods, which means they are local variables, and they are recreated each time those methods run. This isn't what you want. You either want to pass them from one method to the next, as parameters; or to have them as fields of your class.

Using loops to compute factorial numbers, Java

I'm trying to compute the value of 7 factorial and display the answer, but when I tried to look up a way to do this I kept finding code that was written so that a number first had to be put in from the user and then it would factor whatever number the user put in. But I already know what number I need, obviously, so the code is going to be different and I'm having trouble figuring out how to do this.
I tried this at first
public class Ch4_Lab_7
{
public static void main(String[] args)
{
int factorial = 7;
while (factorial <= 7)
{
if (factorial > 0)
System.out.println(factorial*facto…
factorial--;
}
}
}
But all it does is display 7*7, then 6*6, then 5*5, and so on, and this isn't what I'm trying to do.
Does anyone know how to do it correctly?
import java.util.Scanner;
public class factorial {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
//Gives Prompt
System.out.print("Enter a number to find the factorial of it");
//Enter the times you want to run
int number = input.nextInt();
//Declares new int
int factor = 1;
//Runs loop and multiplies factor each time runned
for (int i=1; i<=number; i++) {
factor = factor*i;
}
//Prints out final number
System.out.println(factor);
}
}
Just keep multiplying it and until it reaches the number you inputted. Then print.
Input:5
Output:120
input:7
Output:5040
You need to have two variables, one for the factorial calculation and other for the purpose of counter. Try this, i have not tested it but should work:
public static void main(String[] args)
{
int input = 7;
int factorial = 1;
while (input > 0)
{
factorial = factorial * input
input--;
}
System.out.println("Factorial = " + factorial);
}
int a=7, fact=1, b=1;
do
{
fact=fact*b;//fact has the value 1 as constant and fact into b will be save in fact to multiply again.
System.out.print(fact);
b++;
}
while(a>=b); // a is greater and equals tob.
1st reason:
The methods you seen are probably recursive, which you seem to have edited.
2nd:
You are not storing, ANYWHERE the temporal results of factorial.
Try this
//number->n for n!
int number = 7;
//We'll store here the result of n!
int result = 1;
//we start from 7 and count backwards until 1
while (number > 0) {
//Multiply result and current number, and update result
result = number*result;
//Update the number, counting backwards here
number--;
}
//Print result in Screen
System.out.println(result);
Try this:
public static void main(String args[]) {
int i = 7;
int j = factorial(i); //Call the method
System.out.println(j); //Print result
}
public static int factorial(int i) { //Recursive method
if(i == 1)
return 1;
else
return i * factorial(i - 1);
}
This would print out the factorial of 7.
public class Factorial {
public static void main(String[] args) {
int result = factorial(5); //this is where we do 5!, to test.
System.out.println(result);
}
public static int factorial(int n) {
int x = 1;
int y = 1;
for (int i = 1; i <= n; i++) {
y = x * i;
x = y;
}
return y;
}
}
/*so, for 3! for example, we have:
i=1:
y = x * i, where x = 1, so that means:
y = 1*1 ; y= 1; x = y so x = 1. Then i increments =>
i = 2:
y = x * i. x is 1 and i is 2, so we have y = 2. Next step in code: x=y, means x = 2. Then i increments =>
i = 3:
y = x *i so we have y = 2*3. y=6. */

Java Program Calculation

Write a program in Java to calculate the following:
1+2-3+4-5 …-99+100
this program is provably very simple but I am a beginner to java and this is what i have so far I'm not sure if i am in the right path
I get one java: 13 error message error:not a statement sub;
class Loop{
public static void main(String[] args){
int sum=0;
int sum=0;
int sub=0;
while(num<100){
num++;
if(num%2 == 0){
sum=sum+num;
}
sub;
if(num%3== 0||num%5==0||num%7==0){
sub=sub-num;
}
}
System.out.println("Sum is: " +sum+sub);
}
}
This is complaining about this line:
sub;
This is not a valid instruction, which is why the compiler is yelling at you.
In the following:
if(num%2 == 0){
sum=sum+num;
}
sub;
That last line sub; is not a Java statement. You probably want to delete it.
Update:
Looks like you want to add even and subtract odd (except for 1 which you want to add). If I understood the requirement properly:
You can start by declaring two variables as follows:
int sum = 1; //this will add 1
int n = 2;
Loop condition should be as follows:
while(n <= 100) { //because you want to include 100 also
Then on each iteration of the loop:
If n is even add it to sum, else if n is odd subtract it from sum.
After that increment n by 1.
Finally, print the value of sum.
You can using simple way to implement it :
public static void main(String[] args) {
int sum = 1;
for (int i = 2; i < 100; i++) {
if (i % 2 == 0) {
sum = sum + i;
} else {
sum = sum - i;
}
}
System.out.println(sum);
}
class Loop{
public static void main(String[] args){
int sum=0;
int sum=0;
int sub=0;
while(num<100){
num++;
if(num%2 == 0){
sum=sum+num;
}
sub; <-- sub is not a statment
if(num%3== 0||num%5==0||num%7==0){
sub=sub-num;
}
}
System.out.println("Sum is: " +sum+sub);
}
}
You are on the right track, with a little trial and error you will get it :-) The cause of your problem is commented in the code above, in the middle of your program you have a random sub; on its own line. sub doesn't have a meaning in that context so the compiler doesn't know how to treat it.
1) You can't have 2 variables with the same name sum
2) You need to declare and initialize a variable before you use it
3) What does the statement sub; signify?
Make all the chages mentioned above and try!
Well, you declare "sum" twice, and "sub;" isn't a valid expression.
class Loop{
public static void main(String[] args){
int sum=0;
int sum=0; // second declaration? should probably be num, right?
int sub=0;
while(num<100){
num++;
if(num%2 == 0){
sum=sum+num;
}
sub; // what's this doing here?
if(num%3== 0||num%5==0||num%7==0){
sub=sub-num;
}
}
System.out.println("Sum is: " +sum+sub);
}
}
public class Loop {
public static void main(String[] args) {
int sum = 1;
int sub = 0;
for (int i = 2; i <= 100; i += 2)
//sum =sum+i;
sum +=i;
System.out.println(sum);
for (int i = 3; i <= 100; i += 2)
sub += i;
System.out.println(sub);
System.out.println("Sum is: " +(sum-sub));
}
}
Try this code will give you your desired result

Categories

Resources