In my program Logic is like:--
Input Addition with Output(result)
2 3 5
3 3+4 10
4 3+4+4 15
5 3+4+4+4 20
6 3+4+4+4+4 25
So, I have made:--
import java.util.Scanner;
public class Addition {
public static void main( String[] args) {
@SuppressWarnings("resource")
Scanner s = new Scanner(System.in);
int result=0;
System.out.print("Enter a number: ");
int inputNumber = s.nextInt();
if(inputNumber==2){
result = inputNumber+3;
}
else{
Addition c=new Addition();
int j = inputNumber-2;
int power=c.pow(4,j);
result = inputNumber+3+power;
}
System.out.print(result);
}
int pow(int c, int d)
{
int n=1;
for(int i=0;i<d;i++)
{
n=c*n;
}
return n;
}
}
In this program I am getting result:--
Input Output(result)
2 5
3 10
4 23
5 72
why? What Am I doing wrong??
You're confusing 'power of' with multiplication.
int power=c.pow(4,j);
should simply be:
int power= 4 * j;
You are calculating j correctly, its value will be 1 for inputNumber 3, 2 for inputNumber 4 and so on ...But You are not using it correctly. Note we are not adding powers of 4(4,16,64..), we are simply adding multiples of 4 in increasing order(4,8,12,..). So you should be adding 4*j to calculate the result
Change your code as follows:-
int j = inputNumber-2;
int multiple=4*j;
result = inputNumber+3+multiple;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.