PrintPowersof2 in java - java

Write a method called printPowersOf2 that accepts a maximum number as an argument and prints each power of 2 from 20 (1) up to that maximum power, inclusive. For example, consider the following calls:
printPowersOf2(3);
printPowersOf2(10);
These calls should produce the following output:
1 2 4 8
1 2 4 8 16 32 64 128 256 512 1024
yes, this is a homework problem and I am sorry. I am not asking for code or anything just a little guidance would be helpful and I want to know what I am doing is wrong. Thank You.
import java.lang.Math;
public class Power {
public void printPowersOf2(double thisX){
double k = 1.0;
for(double i = k; i <= Math.pow(2,thisX); i++){
double square = k;
System.out.print(square+" ");
k = 2.0 * k;
}
}
}
Second Class:
import java.util.*;
public class PowerMain{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Please, enter a number you want to square: ");
double exponents = input.nextDouble();
Power numberOfPower = new Power();
numberOfPower.printPowersOf2(exponents);
}
}
My output =
1.0 2.0 4.0 8.0 16.0 32.0 64.0 128.0 > when i enter 3

Your issue is the line
for(double i = k; i <= Math.pow(2,thisX); i++)
The reason why is because the following code produces the value 8 when the input is 3
Math.pow(2,thisX)
If you notice, you have 8 output values which comes from 2^3. You should just be looping 3 times (instead of your current 8), so you should really just do the following
for(int i = 0; i < thisX; i++)
...

You want to get the power of 2 for each number 0 to thisX so you should change your loop like:
for(double i = 0; i <= thisX; i++)
You should be looping from 0 to your number adding 1 each loop and for each iteration take that number ^ 2 like 0^2 print 1^2 print 2^2 print 3^2 print...

Related

Why comes infinite while loop in my code and value not come Zero?

I am writing a code of program that reverse my input, the code that I had written is look like this:
/*
* Author: Mohammed Khalid Alnahdi
*
* This program is reverse the number.
* for example 123 to 321
*
*/
// call utility to take number from the users.
import java.util.Scanner;
class ReverseNumberInput{
public static void main(String[] args){
//we call the tool of take number.
Scanner take = new Scanner(System.in);
int inputNumberUser, printValue = 0;
System.out.print("Please enter the number : ");
inputNumberUser = take.nextInt();
System.out.print("the reverse number is : ");
while(inputNumberUser != 0){
printValue = inputNumberUser % 10;
inputNumberUser = inputNumberUser- printValue;
System.out.printf("%d",printValue);
}
}
}
The answer comes for solve this problem by two why
first solution is replace
inputNumberUser = inputNumberUser- printValue;
by
inputNumberUser = inputNumberUser/10;
and second one is by
while(inputNumberUser != 0){
int digit = inputNumberUser % 10;
printValue = printValue * 10 + digit;
inputNumberUser = inputNumberUser/10;
}
System.out.print(printValue);
My Question why my code in the first not give inputNumberUser zero value while deducting remaining till put the value is zero.
You need to divide the resul of subtraction
inputNumberUser = inputNumberUser- printValue; by 10 after each iteration
For example, you have an input 154
154 - 4 = 150 is your next inputNumberUser
and in the next iteration you have
150 - 0 = 150 is your next inputNumberUser
So your output will be 40000...
If you divide inputNumberUser by 10 after each iteration, you will have
15 - 5 = 10 is your next inputNumberUser
then,
1 - 1 = 0 is your next inputNumberUser

How can i determine the formula for determining the first number in Java's loop array for floyd's triangle?

Hi so i have java loop problem.
So i'm trying to figure out how to determine the first number(in the top of the pattern) in the loop for floyd's triangle by entering the height on the triangle.
Note: only the height is to be inputted to determine the first number and the last number should be fixed to 1.
for example:
Enter the height: 5
The first number is: 15
15
14 13
12 11 10
9 8 7 6
5 4 3 2 1
Another one is
Enter the height: 6
The first number is: 21
21
20 19
18 17 16
15 14 13 12
11 10 9 8 7
6 5 4 3 2 1
I've figured out how to do the pattern and the decrementing of the value but i cant seem to figure out the first number. I've been trying to figure out the sequence but it's still confusing to me because i'm still new at java.
Here is my code:
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
int n;
int startingnumber = ;
Scanner input = new Scanner(System.in);
System.out.print("Enter the height of the triangle: ");
n = input.nextInt();
System.out.print("The first number is "+startingnumber);
for(int i =1; i<=n; i++){
for(int j =1; j<=i; j++){
System.out.print(startingnumber);
startingnumber--;
}
System.out.println();
}
}
}
The code is still not finished because i cant figure out the formula :(
I would appreciate any help that i can find. Thanks!
This mathematical problem is Triangular number and here is a visual demonstration
S1 = 1
S2 = 1 + 2
S3 = 1 + 2 + 3
...
Sn = 1 + 2 + 3 + ... + n
=> 1 + 2 + 3 + ... + n = n * (n + 1) / 2
An also have a look at System.out.printf
public static void main(String[] args) {
int n;
int startingnumber;
Scanner input = new Scanner(System.in);
System.out.print("Enter the height of the triangle: ");
n = input.nextInt();
startingnumber = n * (n + 1) / 2;
System.out.println("The first number is " + startingnumber);
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
System.out.printf("%3d ", startingnumber);
startingnumber--;
}
System.out.println();
}
}
Output
Enter the height of the triangle: 6
The first number is 21
21
20 19
18 17 16
15 14 13 12
11 10 9 8 7
6 5 4 3 2 1
The way you solve that type of question is by finding a mathematical relationship. In this case, you know (when input's 6) that the height's 6. You also know that at each row, you have one less number than at the one that goes after it. The bottom one has 6, as its the same as the height.
Therefore, you need to do 6+5+4+3+2+1 to obtain the starting number.
Now that formulated as a generic solution: n+(n-1)+((n-1)-1)..+1.
A possible implementation for that is:
System.out.print("Enter the height of the triangle: ");
n = input.nextInt();
int startingNumber = 0;
for (int i=n;i>0;i--) startingNumber+=i;

How do I print the percentage once I have the Sum and Frequency of a number?

I am having trouble getting the percentage of the frequency to print. Below is the question:
Write a program to simulate the rolling of two dice. The program should use an object of class Random once to roll the first die and again to roll the second die. The sum of the two values should then be calculated. Each die can show an integer value from 1 to 6, so the sum of the values will vary from 2 to 12, with 7 being the most frequent sum and 2 and 12 being the least frequent sums. Your application should roll the dice 36,000 times. Use a one dimensional array to keep track of the number of times each possible sum appears. Display the results in tabular format. Determine whether the totals are reasonable (e.g., here are six ways to roll a 7, so approximately one-sixth of the rolls should be 7). Sample output:
Sum Frequency Percentage
2 1027 2.85
3 2030 5.64
4 2931 8.14
5 3984 11.07
6 5035 13.99
7 5996 16.66
8 4992 13.87
9 4047 11.24
10 2961 8.23
11 1984 5.51
12 1013 2.81
This is my code so far:
import java.util.Random;
public class dice_roll {
public static void main(String [] args){
Random rand = new Random();
int dice1, dice2;
int [] frequency = new int [13];
int [] rolls = new int [13];
int sum;
double percentage;
for (int i = 0; i <= 36000; i++) {
dice1 = rand.nextInt(6)+1;
dice2 = rand.nextInt(6)+1;
frequency[dice1+dice2]++;
sum = dice1 + dice2;
}
System.out.printf("Sum\tFrequency\tPercentage\n");
for (int i = 2; i < frequency.length; i++) {
percentage = (frequency[i] * 100.0) / 36000;
System.out.printf("%d\t%d\t\n",i,frequency[i]);//this line here
}
}
}
First of all, your for loop is off by 1:
for (int i = 0; i <= 36000; i++) {
// ^
// remove this "=" or you will loop 36001 times
Your sum seems redundant, so remove that as well.
I think you just don't know how to format the output so that the floats correct to 2 d.p. right?
It's easy. Just add do %.2f!
Your printf will be like:
System.out.printf("%d\t%d\t%.2f\n",i,frequency[i], percentage);
Another problem with your code is that it might produce unaligned stuff. It also does not align the values to the right as the sample output shows. To fix this, you also just need to change the printf. Like this:
System.out.printf("%3d\t%9d\t%10.2f\n",i,frequency[i], percentage);
If you want to read more about how printf works, list here.
Stealing from this answer: we can use padRight which is defined as:
public static String padRight(String s, int n) {
return String.format("%1$-" + n + "s", s);
}
and do:
System.out.printf("Sum\tFrequency\tPercentage\n");
for (int i = 2; i < frequency.length; i++) {
String s = padRight(String.valueOf(i), 4);
String f = padRight(String.valueOf(frequency[i]), 12);
percentage = (frequency[i] * 100.0) / 36000;
String p = String.format("%.2f", percentage); // This formatting will keep two digits after the point
System.out.printf("%s%s%s\n", s ,f, p);
}
OUTPUT (example)
Sum Frequency Percentage
2 992 2.76
3 2031 5.64
4 3034 8.43
5 3947 10.96
6 4887 13.58
7 5948 16.52
8 4965 13.79
9 4051 11.25
10 3014 8.37
You can play with it and remove the \t from the first line and use spaces instead in order to create the amount of spacing you want between the columns and then pass the second parameter in the calls to padRight accordingly.

Wrong results for bigger values

I was trying a programming problem, the statement is
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Like this we have to find the sum of multiples for 't' test cases with 'n' value each, I have tried to find the solution and my code is
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
long t,n,sum;
Scanner in=new Scanner(System.in);
t=in.nextLong();
for(int i=0;i<t;i++)
{
sum=0;
n=in.nextLong();
long l3=0,l5=0,l15=0;
for(int j=3;j>0;j--)
if((n-j)%3==0&&j<n)
{
l3=n-j;
break;
}
for(int j=5;j>0;j--)
if((n-j)%5==0&&j<n)
{
l5=n-j;
break;
}
for(int j=15;j>0;j--)
if((n-j)%15==0&&j<n)
{
l15=n-j;
break;
}
sum+=(float)(((float)l3/(float)3)/(float)2)*(float)(l3+3);
sum+=(float)(((float)l5/(float)5)/(float)2)*(float)(l5+5);
sum-=(float)(((float)l15/(float)15)/(float)2)*(float)(l15+15);
System.out.println(sum);
}
}
}
And the input I gave was,
12
10
11
12
13
1000
1001
1002
1003
100000000
100000001
100000002
100000003
Here 12 is the number of test cases.
And the output I got was
23
33
33
45
233168
234168
234168
235170
2333333593784320
2333333593784320
2333333593784320
2333333593784320
The problem here is the answer is correct for values in the test case 10,11,12,13,1000,1001,1002,1003 but the output is wrong for remaining bigger inputs. I cant find what i am missing. Could you please help me on why I am getting this kind of wrong result and how to rectify it.
You can get a higher precision and a larger numbers by using BigDecimal and BigInteger:
package test;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
long t,n;
BigInteger sum;
Scanner in=new Scanner(System.in);
t=in.nextLong();
for(int i=0;i<t;i++)
{
sum = BigInteger.ZERO;
n=in.nextLong();
long l3=0,l5=0,l15=0;
for(int j=3;j>0;j--)
if((n-j)%3==0&&j<n)
{
l3=n-j;
break;
}
for(int j=5;j>0;j--)
if((n-j)%5==0&&j<n)
{
l5=n-j;
break;
}
for(int j=15;j>0;j--)
if((n-j)%15==0&&j<n)
{
l15=n-j;
break;
}
BigDecimal x = BigDecimal.valueOf(l3)
.divide(BigDecimal.valueOf(6))
.multiply(BigDecimal.valueOf(l3+3));
sum=sum.add(x.toBigIntegerExact());
x = BigDecimal.valueOf(l5)
.divide(BigDecimal.valueOf(10))
.multiply(BigDecimal.valueOf(l5+5));
sum=sum.add(x.toBigIntegerExact());
x = BigDecimal.valueOf(l15)
.divide(BigDecimal.valueOf(30))
.multiply(BigDecimal.valueOf(l15+15));
sum=sum.subtract(x.toBigIntegerExact());
System.out.println(sum);
}
}
}
Without deeper analysis of your code I would guess the problem is that you are using float, which has a quite short value range. Could you try double instead? Not sure what the correct answer would be, but at least you get different results (I just tried)
The solution looks too complex for such a task. I don't understand why do you need to perform the divisions at the end. You can try the following code:
int t = <some number> // the upper bound
int[] dividers = [...] // those are divisors against which we have to test
long sum = 0;
// check all the number up the bound
for (int number = 1; number < t; number++) {
for (int i = 0; i < dividers.length; i++) {
if (number % dividers[i] == 0) {
// the number is divisible without remainder -> add it to the sum
sum += number;
break;
}
}
}
The idea is to iterate all the numbers you want to check and see if they are divisible by some of the N dividers. If you find a number, you add it to the sum and continue with the next one.
Edit:
After the clarifications from OP, I came up with another way to do this.
int t = <some number> // the upper bound
int dividers = [3, 5];
int dividerProduct = dividers[0] * dividers[1];
long sum = calculateSumForDivider(dividers[0], t) + calculateSumForDivider(dividers[1], t) - calculateSumForDivider(dividerProduct, t);
public static int calculateSumForDivider(int divider, int number) {
int n = number / divider;
return divider * n * (n + 1) / 2;
}
What is the logic behind all this?
By dividing the target number, we can calculate how many times does the divider "fit" in the target. This is also the number of numbers in the interval [1, number] that are divisible by the divider. Let's see an example:
t = 10, divider = 3
10 / 3 = 3, so they are 3 numbers in the interval [1, 10], divisible by 3
the numbers are: 1 * 3, 2 * 3, 3 * 3
if we calculate the sum we get 1 * 3 + 2 * 3 + 3 * 3 = 3 * (1 + 2 + 3) = 18
analogically, for = 10, divider = 5
10 / 5 = 2
1 * 5 + 2 * 5 = 5 * (1 + 2) = 15
As a conclusion, we have the following formula for the sum:
sum = divider * n * (n + 1) / 2
where n is the result of the division.
The gotcha here is that numbers, divisible by both 3 and 5 (in other words divisible by 15) are going to be added twice to the sum. To correct this we use the same formula as above to calculate their sum and subtract it from the resulting some, reaching the result.
This solution will only work well for 2 dividers, since with multiple the number of numbers that will be added multiple times to the sum will grow exponentially. F.e. if we want to divide be 3, 4 or 5, we will need to take care of 12, 15, 20, 60, etc.
This will also not work if the two one of the dividers is a power of the other, like 3 and 9. In that case we only need the numbers, divisible by 3.
I am not sure about your algorithm because the simplest one should be like:
sum=0;
n=100100000;
for(int j=1;j<n;j++)
if(j%3==0 || j%5==0)
{
sum+=j;
}
System.out.println(sum);
System.out.println(n*n);
And to get a better idea on what should be the result, it is always less than n*n.
The output I found was:
2338002249916668
10020010000000000
So, as your results where less than n*n, if you are sure about you algorithm, then they are correct.

Printing Odd numbers in a upside down right angle formation

Im trying to take a number and print it's odd number like this:
if i take 5 as a number it should give this:
1 3 5
3 5
5
and if i take 9 it should do the same thing:
1 3 5 7 9
3 5 7 9
5 7 9
7 9
9
This is what i have so far and i am stuck. i can't get the 5 to print after the 3 and to end it with 5 for the triangle:
public class first{
static void afficher(int a){
for(int i=1;i<=a;i++){
if(i%2!=0){
System.out.printf("%d",i);
}
}
System.out.println();
for(int j=3;j<=a-2;j++){
if(j%2!=0){
System.out.printf("%d",j);
}
}
}
public static void main(String[]args){
afficher(5);
}
}
This prints:
1 3 5
3
If you print a surface (2d thus), one expects that the algorithm runs in O(n^2) time complexity. Thus two nested fors:
public class first{
static void afficher(int a){
for(int i = 1; i <= a; i += 2) {
for(int j = i; j <= a; j += 2){
System.out.print(j);
System.out.print(' ');
}
System.out.println();
}
}
}
One can optimize the algorithm a bit by not checking if the number is odd, but taking steps of 2.
See demo.
You have to use nested for-loops to resolve this problem. Go through the following code
public class OddNumberLoop {
public static void main(String[] args) {
Scanner inpupt = new Scanner(System.in);
System.out.print("Input the starting number : ");
int start = inpupt.nextInt();
for(int i = 1 ; i <= start; i += 2){
for(int x = i; x <= start; x += 2) System.out.print(x+ " ");
System.out.println();
}
}
}
The reason it is printing as follows because:
1 3 5 -> your i loop runs here (from 1 to 5)
3 -> your j loop runs here (from 3 to (less than OR equal to 5))
So I suggest the following:
Use 2 nested loops (for universal values):
i running from 1 to the input number increasing by 2
j running from i to the input number increasing by 2 also ending with line change'/n'
Keep a check whether the input number is odd or not.

Categories

Resources