find the sum of the multiples of 3 and 5 below 1000 - java

Ok guys, so I'm doing the Project Euler challenges and I can't believe I'm stuck on the first challenge. I really can't see why I'm getting the wrong answer despite my code looking functional:
import java.util.ArrayList;
public class Multithree {
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<Integer> x = new ArrayList<Integer>();
ArrayList<Integer> y = new ArrayList<Integer>();
int totalforthree = 0;
int totalforfive = 0;
int total =0;
for(int temp =0; temp < 1000 ; temp++){
if(temp % 3 == 0){
x.add(temp);
totalforthree += temp;
}
}
for(int temp =0; temp < 1000 ; temp++){
if(temp % 5 == 0){
y.add(temp);
totalforfive += temp;
}
}
total = totalforfive + totalforthree;
System.out.println("The multiples of 3 or 5 up to 1000 are: " +total);
}
}
I'm getting the answer as 266333 and it says it's wrong...

you should use the same for loop for both to aviod double counting numbers that are multiple of both. such as 15,30...
for(int temp =0; temp < 1000 ; temp++){
if(temp % 3 == 0){
x.add(temp);
totalforthree += temp;
}else if(temp % 5 == 0){
y.add(temp);
totalforfive += temp;
}
}

In a mathematical perspective,
You did not consider about common factors between 3 and 5.Because there is double counting.
ex; number 15 ,
30 ,
45 ,
60 ,
75 ,
90 ,
105 ,
120 ,
135 ,
150 ,
165 ,
180 ,
195 ,
210 ,
225 ,
240 ,
255 ,
270 ,
285 ,
300 ,
315 ,
330 ,
345 ,
360 ,
375 ,
390 ,
405 ,
420 ,
435 ,
450 ,
465 ,
480 ,
495 ,
510 ,
525 ,
540 ,
555 ,
570 ,
585 ,
600 ,
615 ,
630 ,
645 ,
660 ,
675 ,
690 ,
705 ,
720 ,
735 ,
750 ,
765 ,
780 ,
795 ,
810 ,
825 ,
840 ,
855 ,
870 ,
885 ,
900 ,
915 ,
930 ,
945 ,
960 ,
975 ,
990 , are common factors.
total of common factors = 33165.
Your answer is 266333
Correct answer is 233168.
Your Answer - Total of common factors
266333-33165=233168.
(this is a code for getting common factors and Total of common factors )
public static void main(String[] args) {
System.out.println("The sum of the Common Factors : " + getCommonFactorSum());
}
private static int getCommonFactorSum() {
int sum = 0;
for (int i = 1; i < 1000; i++) {
if (i % 3 == 0 && i % 5 == 0) {
sum += i;
System.out.println(i);
}
}

Don't you all think instead of using loops to compute the sum of multiples, we can easily compute sum of n terms using a simple formula of Arithmetic Progression to compute sum of n terms.
I evaluated results on both using loop and formula. Loops works simply valuable to short data ranges. But when the data ranges grows more than 1010 program takes more than hours to process the result with loops. But the same evaluates the result in milliseconds when using a simple formula of Arithmetic Progression.
What we really need to do is:
Algorithm :
Compute the sum of multiples of 3 and add to sum.
Compute the sum of multiples of 5 and add to sum.
Compute the sum of multiples of 3*5 = 15 and subtract from sum.
Here is code snippet in java from my blog post CodeForWin - Project Euler 1: Multiples of 3 and 5
n--; //Since we need to compute the sum less than n.
//Check if n is more than or equal to 3 then compute sum of all divisible by
//3 and add to sum.
if(n>=3) {
totalElements = n/3;
sum += (totalElements * ( 3 + totalElements*3)) / 2;
}
//Check if n is more than or equal to 5 then compute sum of all elements
//divisible by 5 and add to sum.
if(n >= 5) {
totalElements = n/5;
sum += (totalElements * (5 + totalElements * 5)) / 2;
}
//Check if n is more than or equal to 15 then compute sum of all elements
//divisible by 15 and subtract from sum.
if(n >= 15) {
totalElements = n/15;
sum -= (totalElements * (15 + totalElements * 15)) / 2;
}
System.out.println(sum);

If you are using Java 8 you can do it in the following way:
Integer sum = IntStream.range(1, 1000) // create range
.filter(i -> i % 3 == 0 || i % 5 == 0) // filter out
.sum(); // output: 233168
To count the numbers which are divisible by both 3 and 5 twice you can
either write the above line twice or .map() the 2 * i values:
Integer sum = IntStream.range(1, 1000)
.filter(i -> i % 3 == 0 || i % 5 == 0)
.map(i -> i % 3 == 0 && i % 5 == 0 ? 2 * i : i)
.sum(); // output: 266333

How I solved this is that I took an integer value (initialized to zero) and kept on adding the incremented value of i, if its modulo with 3 or 5 gives me zero.
private static int getSum() {
int sum = 0;
for (int i = 1; i < 1000; i++) {
if (i % 3 == 0 || i % 5 == 0) {
sum += i;
}
}
return sum;
}

I did this several ways and several times. The fastest, cleanest and simplest way to complete the required code for Java is this:
public class MultiplesOf3And5 {
public static void main(String[] args){
System.out.println("The sum of the multiples of 3 and 5 is: " + getSum());
}
private static int getSum() {
int sum = 0;
for (int i = 1; i < 1000; i++) {
if (i % 3 == 0 || i % 5 == 0) {
sum += i;
}
}
return sum;
}
If anyone has a suggestion to get it down to fewer lines of code, please let me know your solution. I'm new to programming.

int count = 0;
for (int i = 1; i <= 1000 / 3; i++)
{
count = count + (i * 3);
if (i < 1000 / 5 && !(i % 3 == 0))
{
count = count + (i * 5);
}
}

Others have already pointed out the mistakes in your code, however I want to add that the modulus operator solution is not the most efficient.
A faster implementation would be something like this:
int multiply3_5(int max)
{
int i, x3 = 0, x5 = 0, x15 = 0;
for(i = 3; i < max; i+=3) x3 += i; // Store all multiples of 3
for(i = 5; i < max; i+=5) x5 += i; // Store all multiples of 5
for(i = 15; i < max; i+=15) x15 += i; // Store all multiples 15;
return x3+x5-x15;
}
In this solution I had to take out multiples of 15 because, 3 and 5 have 15 as multiple so on the second loop it will add multiples of 15 that already been added in the first loop;
Solution with a time complexity of O(1)
Another even better solution (with a time complexity of O(1)) is if you take a mathematical approach.
You are trying to sum all numbers like this 3 + 6 + 9 ... 1000 and 5 + 10 + 15 +20 + ... 1000 this is the same of having 3 * (1 + 2 + 3 + 4 + … + 333) and 5 * ( 1 + 2 + 3 + 4 + ... + 200), the sum of 'n' natural number is (n * (n + 1)) (source) so you can calculate in a constant time, as it follows:
int multiply3_5(int max)
{
int x3 = (max - 1) / 3;
int x5 = (max - 1) / 5;
int x15 = (max - 1) / 15;
int sn3 = (x3 * (x3 + 1)) / 2;
int sn5 = (x5 * (x5 + 1)) / 2;
int sn15 = (x15 * (x15 + 1)) / 2;
return (3*sn3) + (5 *sn5) - (15*sn15);
}
Running Example:
public class SumMultiples2And5 {
public static int multiply3_5_complexityN(int max){
int i, x3 = 0, x5 = 0, x15 = 0;
for(i = 3; i < max; i+=3) x3 += i; // Store all multiples of 3
for(i = 5; i < max; i+=5) x5 += i; // Store all multiples of 5
for(i = 15; i < max; i+=15) x15 += i; // Store all multiples 15;
return x3 + x5 - x15;
}
public static int multiply3_5_constant(int max){
int x3 = (max - 1) / 3;
int x5 = (max - 1) / 5;
int x15 = (max - 1) / 15;
int sn3 = (x3 * (x3 + 1)) / 2;
int sn5 = (x5 * (x5 + 1)) / 2;
int sn15 = (x15 * (x15 + 1)) / 2;
return (3*sn3) + (5 *sn5) - (15*sn15);
}
public static void main(String[] args) {
System.out.println(multiply3_5_complexityN(1000));
System.out.println(multiply3_5_constant(1000));
}
}
Output:
233168
233168

Just simply
public class Main
{
public static void main(String[] args) {
int sum=0;
for(int i=1;i<1000;i++){
if(i%3==0 || i%5==0){
sum+=i;
}
}
System.out.println(sum);
}
}

You are counting some numbers twice. What you have to do is add inside one for loop, and use an if-else statement where if you find multiples of 3, you do not count them in 5 as well.
if(temp % 3 == 0){
x.add(temp);
totalforthree += temp;
} else if(temp % 5 == 0){
y.add(temp);
totalforfive += temp;
}

Logics given above are showing wrong answer, because multiples of 3 & 5 are taken for calculation. There is something being missed in above logic, i.e., 15, 30, 45, 60... are the multiple of 3 and also multiple of 5. then we need to ignore such while adding.
public static void main(String[] args) {
int Sum=0, i=0, j=0;
for(i=0;i<=1000;i++)
if (i%3==0 && i<=999)
Sum=Sum+i;
for(j=0;j<=1000;j++)
if (j%5==0 && j<1000 && j*5%3!=0)
Sum=Sum+j;
System.out.println("The Sum is "+Sum);
}

Okay, so this isn't the best looking code, but it get's the job done.
public class Multiples {
public static void main(String[]args) {
int firstNumber = 3;
int secondNumber = 5;
ArrayList<Integer> numberToCheck = new ArrayList<Integer>();
ArrayList<Integer> multiples = new ArrayList<Integer>();
int sumOfMultiples = 0;
for (int i = 0; i < 1000; i++) {
numberToCheck.add(i);
if (numberToCheck.get(i) % firstNumber == 0 || numberToCheck.get(i) % secondNumber == 0) {
multiples.add(numberToCheck.get(i));
}
}
for (int i=0; i<multiples.size(); i++) {
sumOfMultiples += multiples.get(i);
}
System.out.println(multiples);
System.out.println("Sum Of Multiples: " + sumOfMultiples);
}
}

public class Solution {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while (t>0){
int sum = 0;
int count =0;
int n = sc.nextInt();
n--;
System.out.println((n/3*(6+(n/3-1)*3))/2 + (n/5*(10+(n/5-1)*5))/2 - (n/15*(30+(n/15-1)*15))/2);
t--;
}
}
}

If number is 10 then multiple of 3 is 3,6,9 and multiple of 5 is 5,10 total sum is 33 and program gives same answer:
package com.parag;
/*
* #author Parag Satav
*/
public class MultipleAddition {
/**
* #param args
*/
public static void main( final String[] args ) {
// TODO Auto-generated method stub
ArrayList<Integer> x = new ArrayList<Integer>();
ArrayList<Integer> y = new ArrayList<Integer>();
int totalforthree = 0;
int totalforfive = 0;
int number = 8;
int total = 0;
for ( int temp = 1; temp <= number; temp++ ) {
if ( temp % 3 == 0 ) {
x.add( temp );
totalforthree += temp;
}
else if ( temp % 5 == 0 ) {
y.add( temp );
totalforfive += temp;
}
}
total = totalforfive + totalforthree;
System.out.println( "multiples of 3 : " + x );
System.out.println( "multiples of 5 : " + y );
System.out.println( "The multiples of 3 or 5 up to " + number + " are: " + total );
}
}

Related

Troubleshooting java script maximum / minimium / average / barchart code 2 classes 4 function methods

My goal is to have it output the min max avg and a barchart.
`
package arraystuff1;
import java.util.Random;
public class problem1
{
public static void main(String[] args)
{
int min=0;
int max=0;
int avg=0;
//initialize array
Random randomNumbers = new Random();
final int Length = 30;
int[] array1 = new int[Length];
for ( int counter = 0; counter < array1.length; counter++ )
{
array1[ counter ] = 1+randomNumbers.nextInt( 100 );
}
//array tested and produces correct output
for ( int counter = 0; counter < array1.length; counter++ )//minimum
{
min = functionsp1.min(array1[counter],min);
if(counter == Length-1)
System.out.printf("The minimum value is: %d\n",min);
}
for ( int counter = 0; counter < array1.length; counter++ )//maximum
{
max = functionsp1.max(array1[counter],max);
if(counter == Length-1)
System.out.printf("The maximum value is: %d\n",max);
}
for ( int counter = 0; counter < array1.length; counter++ )//average
{
avg = functionsp1.avg(array1[counter],Length);
if(counter == Length-1)
System.out.printf("The average value is: %d\n",avg);
}
for ( int counter = 0; counter < array1.length; counter++ )//average
{
functionsp1.bar(array1[counter],Length);//print a line showing range of the bar graph use switch case to build frequencies for each 10th unit
functionsp1.freq(array1[counter],Length);//print stars representing number of random numbers that fit in this category
}
}
}
`
/////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////
`
package arraystuff1;
public class functionsp1
{
public static int min(int counter,int min)//input array index and length
{
if (counter < min)
{
counter = min;
}
return counter;
}
public static int max(int counter,int max)
{
if (counter > max)
{
counter = max;
}
return counter;
}
public static int avg(int current,int total)//input array length for total and index for current
{
int sum;
int fintotal;
for (int counter = 0; counter < total; counter++ )
{
sum = current + sum; // random number 0-99 add 1 to make it 1-100
if (counter == total)
fintotal = sum/total;
return fintotal;
}
System.out.printf("The average of the array is: %2d",fintotal);
//System.out.printf( "%s%8s\n", "Index", "Value" ); // column headings
return fintotal;
}
public static void bar(int index,int limit)//length and array variable
{
System.out.println("Grade Distribution: ");
for(int counter = 0; counter < limit;counter++)
{
if (counter ==10)
System.out.printf("%5d: ", 100);
else
System.out.printf("%02d-%02d: ",counter*10,counter*10+9);
}
}
public static void freq( int stars )
{
for(int counter=0;counter<stars ; counter ++)
System.out.print("*");
} // end main
}
`
I have verified the array initialized with 30 random numbers in the range of 1-100. My goal is to get the bar chart and the other functions to work but this is the first time I have played with an array any suggestions?
Let your Functionsp1 class methods deal with the Array for example:
//initialize array
java.util.Random randomNumbers = new java.util.Random();
final int length = 30;
int[] array1 = new int[length];
for (int counter = 0; counter < array1.length; counter++) {
array1[counter] = randomNumbers.nextInt(100) + 1;
}
//array tested and produces correct output
Functionsp1 fnctn = new Functionsp1();
int min = fnctn.min(array1);
int max = fnctn.max(array1);
int avg = fnctn.avg(array1);
System.out.printf("The minimum value in array1 is: %d%n", min);
System.out.printf("The maximum value in array1 is: %d\n", max);
System.out.printf("The average value in array1 is: %d\n", avg);
System.out.println("Horizontal Graph For Numerical Range: " + min + " To " + max);
fnctn.bar(array1);
public class Functionsp1 {
public int min(int[] array) {
int min = Integer.MAX_VALUE;
for (int i = 0; i < array.length; i++) {
if (array[i] < min) {
min = array[i];
}
}
return min;
}
public int max(int[] array) {
int max = Integer.MIN_VALUE;
for (int i = 0; i < array.length; i++) {
if (array[i] > max) {
max = array[i];
}
}
return max;
}
public int avg(int[] array) {
int avg = 0;
int sum = 0;
for (int i : array) {
sum += i;
}
avg = sum / array.length;
return avg;
}
public void bar(int[] array) {
System.out.println();
System.out.println("Grade Distribution:");
System.out.println("0 0 10 20 30 40 50"
+ " 60 70 80 90 100");
StringBuilder sb = new StringBuilder("");
for (int i = 0; i < array.length; i++) {
int counter = 0;
for (int j = 0; j < array[i]; j++) {
if ((counter + 1) % 10 == 0) {
sb.append("+");
}
else {
sb.append("|");
}
counter++;
}
System.out.printf("%-3s%-103s(%-3s)%n", (i+1), sb.toString(), array[i]);
sb.setLength(0);
//System.out.printf("%-3s%-100s%n", (i + 1), String.join("", java.util.Collections.nCopies(array[i], "|")));
}
System.out.println();
}
public void freq(int stars) {
for (int counter = 0; counter < stars; counter++) {
System.out.print("*");
}
}
}
I still can't figure out what the freq() method is suppose to accomplish.
As the code above stands right now, if run will produce something like the following in the Console Window:
The minimum value in array1 is: 1
The maximum value in array1 is: 99
The average value in array1 is: 55
Horizontal Graph For Numerical Range: 1 To 99
Grade Distribution:
0 0 10 20 30 40 50 60 70 80 90 100
1 |||||||||+|||| (14 )
2 |||||||||+|||||||||+|||||||||+|||||||||+|||||||||+||||| (55 )
3 |||||||||+|||||||||+|||||||||+|||||||||+|||||||||+|||||||||+|||||||||+|||||||||+|||||||||+ (90 )
4 ||||| (5 )
5 |||||||||+ (10 )
6 |||||||||+|||||||||+|||||||| (28 )
7 |||||||||+|||||||||+|||||||||+|||||||||+|||||||||+|||||||||+|||||||||+|||||||||+|||||||||+|||| (94 )
8 |||||||||+|||||||||+||||||| (27 )
9 |||||||||+|||||||||+|||||||||+|||||||||+|||||||||+|||||||||+|||||||||+|||||||||+|||||||||+| (91 )
10 |||||||||+|||||||||+||||||||| (29 )
11 |||||||||+|||||||||+|||||||||+|||||||||+||||||||| (49 )
12 |||||||||+|||||||||+|||||||||+|||||||||+|| (42 )
13 |||||||||+|||||||||+|||||||||+|||||||||+|||||||||+|||||||||+|||||||||+|||||||||+|||||||||+||||||| (97 )
14 |||||||||+|||||||||+|||||||||+|||||||||+|||||||||+|||||||||+|||||||||+|||||||||+|||||||||+|||| (94 )
15 |||||||||+|||||||||+|||||||||+|||||||||+|||||||||+|||||||||+|||||||||+|||||||||+|||||||||+||||||||| (99 )
16 | (1 )
17 |||||||||+|||||||||+|||||||||+|||||||||+|||||||||+|||||||||+|||||||||+||||||||| (79 )
18 |||||||||+|||||||||+|||||||||+|||||||||+|||||||||+|||||||||+|||||||||+|||||||||+|||||||||+||||| (95 )
19 |||||||||+|||||||||+|||||||||+|||||||||+|||||||||+|||||||||+ (60 )
20 |||||||||+|||||||||+|||||||||+|||||||||+| (41 )
21 |||||||||+||| (13 )
22 |||||||||+|||||||||+|||||||||+|||||||||+|||||||||+|||||||||+|||||||||+|| (72 )
23 |||||||||+|||||||||+|||||||||+|||||||||+|||||||||+|||||||||+|||||||||+||| (73 )
24 |||||||||+|||||||||+||||||| (27 )
25 |||||||||+|||||||||+|||||||||+|||||||||+|||||||||+|||||||||+|||||||||+|||||||||+ (80 )
26 |||||||||+|||||||||+|||||||||+|||||||||+|||||||||+|||||||||+|||||||||+|||||||||+|| (82 )
27 |||||||||+|||||||||+|||||||||+|||| (34 )
28 |||||||||+|||||||||+|||||||||+|||||||||+|||||||||+|||||||||+|||||||||+|||||||||+|||||||||+|||||||| (98 )
29 |||||||||+|||||||||+|||||||||+ (30 )
30 |||||||||+|||||||||+|||||||||+|||||||||+|||||||||+|||| (54 )

My logic doesn't work for computing a histogram

Write a program Example.java to compute data to construct a histogram of integer values read from a file. A histogram is a bar chart in which the length of each bar gives the number of items that fall into a certain range of values, usually called a bin. You won’t actually be drawing a bar chart, but instead will print out the size of each bin.
Your program should take four command line arguments:
The name of a file containing an array of integers
An integer b giving the number of bins to sort into.
A integer min giving the lowest number in the smallest bin.
An integer s giving the size (number of distinct integers) in each bin. You can assume (without checking) that b > 0 and s > 0.
Divide the range of values of interest into b bins of size s. Count the number of values from the file that fall into each bin. Also count the number of values that are completely below or above the range.
For example, given this test file data1:"05X/data1"
1 15
2 18 11 -101 51 92 53 45 55 52 53 54 55 56 5 -2
The output of java Example data1 10 -10 7 should be
x < -10: 1
-10 <= x < -3: 0
-3 <= x < 4: 1
4 <= x < 11: 1
11 <= x < 18: 1
18 <= x < 25: 1
25 <= x < 32: 0
32 <= x < 39: 0
39 <= x < 46: 1
46 <= x < 53: 2
53 <= x < 60: 6
x >= 60: 1
My code below is able to print out the first line of the output. The for loop to print out the range min <= x < max : bin keeps getting the exception
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1 at Example.main(Example.java:49)
What syntax is wrong here? Please help
class Example {
public static void main (String argv[]) throws IOException {
if (argv.length != 4)
usage ();
int[] is = {0};
int b = 0;
int min = 0;
int s = 0;
try {
is = readIntArray(argv[0]);
b = Integer.parseInt (argv[1]);
min = Integer.parseInt (argv[2]);
s = Integer.parseInt(argv[3]);
} catch (NumberFormatException e) {
usage();
}
int max = b * s + min;
int [] count = {0};
for (int i = 0; i < is.length; i++)
if (is[i] < min){
count[0]++;
} else if (i >= max) {
count[b+1]++;
} else {
int n = min;
int index = 0;
while (i < n + s){
n += s;
index++;
count[i]++;
}
}
System.out.println("x < " + min + ": " + count[0]);
for (int i = 1; i <= b; i++){
int low = s * i + min;
int high = s * (i + 1) + min;
System.out.println(low + " <= x < " + high + ": " + count[i]);
}
System.out.println("x >= " + max + ": " + count[b + 1]);
}
Your count array has a length of 1: int [] count = {0}; but you're trying to access higher indices:
if (is[i] < min){
count[0]++;
} else if (i >= max) {
count[b+1]++; //here
} else {
int n = min;
int index = 0;
while (i < n + s){
n += s;
index++;
count[i]++; // and here
}
}
Since indices other that 0 don't exist in the array, they're out of bounds, so you're getting an exception.

Printing odd numbers in odd sequences

There's this problem from my programming class that I can't get right... The output must be all odd numbers, in odd amounts per line, until the amount of numbers per line meets the odd number that was entered as the input. Example:
input: 5
correct output:
1
3 5 7
9 11 13 15 17
If the number entered is even or negative, then the user should enter a different number. This is what I have so far:
public static void firstNum() {
Scanner kb = new Scanner(System.in);
int num = kb.nextInt();
if (num % 2 == 0 || num < 0)
firstNum();
if (num % 2 == 1)
for (int i = 0; i < num; i++) {
int odd = 1;
String a = "";
for (int j = 1; j <= num; j++) {
a = odd + " ";
odd += 2;
System.out.print(a);
}
System.out.println();
}
}
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
firstNum();
}
The output I'm getting for input(3) is
1 3 5
1 3 5
1 3 5
When it really should be
1
3 5 7
Can anyone help me?
Try this:
public static void firstNum() {
Scanner kb = new Scanner(System.in);
int num = kb.nextInt();
while (num % 2 == 0 || num < 0) {
num = kb.nextInt();
}
int odd = 1;
for (int i = 1; i <= num; i += 2) {
String a = "";
for (int j = 1; j <= i; j++) {
a = odd + " ";
odd += 2;
System.out.print(a);
}
System.out.println();
}
}
if (num % 2 == 1) {
int odd = 1;
}
for (int i = 0; i < num; i++) {
String a = "";
for (int j = 1; j <= odd; j++) {
a = odd + " ";
odd += 2;
System.out.print(a);
}
System.out.println();
}
You should assign odd before for loop.
In inner for loop compare j and odd together.
For questions like this, usually there is no need to use and conditional statements. Your school probably do not want you to use String as well. You can control everything within a pair of loops.
This is my solution:
int size = 7; // size is taken from user's input
int val = 1;
int row = (size / 2) + 1;
for (int x = 0; x <= row; x++) {
for (int y = 0; y < (x * 2) + 1; y++) {
System.out.print(val + " ");
val += 2;
}
System.out.println("");
}
I left out the part where you need to check whether input is odd.
How I derive my codes:
Observe a pattern in the desired output. It consists of rows and columns. You can easily form the printout by just using 2 loops.
Use the outer loop to control the number of rows. Inner loop to control number of columns to be printed in each row.
The input number is actually the size of the base of your triangle. We can use that to get number of rows.
That gives us: int row = (size/2)+1;
The tricky part is the number of columns to be printed per row.
1st row -> print 1 column
2nd row -> print 3 columns
3rd row -> print 5 columns
4th row -> print 7 columns and so on
We observe that the relation between row and column is actually:
column = (row * 2) + 1
Hence, we have: y<(x*2)+1 as a control for the inner loop.
Only odd number is to be printed, so we start at val 1 and increase val be 2 each time to ensure only odd numbers are printed.
(val += 2;)
Test Run:
1
3 5 7
9 11 13 15 17
19 21 23 25 27 29 31
33 35 37 39 41 43 45 47 49
You can use two nested loops (or streams) as follows: an outer loop through rows with an odd number of elements and an inner loop through the elements of these rows. The internal action is to sequentially print and increase one value.
a loop in a loop
int n = 9;
int val = 1;
// iterate over the rows with an odd
// number of elements: 1, 3, 5...
for (int i = 1; i <= n; i += 2) {
// iterate over the elements of the row
for (int j = 0; j < i; j++) {
// print the current value
System.out.print(val + " ");
// and increase it
val += 2;
}
// new line
System.out.println();
}
a stream in a stream
int n = 9;
AtomicInteger val = new AtomicInteger(1);
// iterate over the rows with an odd
// number of elements: 1, 3, 5...
IntStream.iterate(1, i -> i <= n, i -> i + 2)
// iterate over the elements of the row
.peek(i -> IntStream.range(0, i)
// print the current value and increase it
.forEach(j -> System.out.print(val.getAndAdd(2) + " ")))
// new line
.forEach(i -> System.out.println());
Output:
1
3 5 7
9 11 13 15 17
19 21 23 25 27 29 31
33 35 37 39 41 43 45 47 49
See also: How do I create a matrix with user-defined dimensions and populate it with increasing values?
Seems I am bit late to post, here is my solution:
public static void firstNum() {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the odd number: ");
int num = scanner.nextInt();
if (num % 2 == 0 || num < 0) {
firstNum();
}
if (num % 2 == 1) {
int disNum = 1;
for (int i = 1; i <= num; i += 2) {
for (int k = 1; k <= i; k++, disNum += 2) {
System.out.print(disNum + " ");
}
System.out.println();
}
}
}

Need help writing a java program that adds multiple digits?

I am trying to write this java program that asks a user for a number and counts the number of digits a number has and multiplies each digit to it's decimal value. For example I enter 546: The program should say this number has 3 digits and should multiply:
5*100=500
4*10=40
1*6=6
So far this is my code: The problems I am having with this code is that it's not counting the right amount of digits. If I enter 545 it says there is only one digit, and when it goes to divides it doesn't give the right answer.
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter a number: ");
int n = keyboard.nextInt();
int i;
for (i = 0; n > 0; i++) {
n /= 10;
for (i = 0; n > 0; i++) {
n /= 10;
System.out.println((n%100000) / 10000);
System.out.println((n%10000) / 1000);
System.out.println((n%1000) / 100);
System.out.println((n%100) / 10);
System.out.println(n%10);
}
System.out.println("Number of digits: " + i);
}
}
The issue is that you have a set of nested for loops that both call n /= 10. It is easier to see if you indent everything:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter a number: ");
int n = keyboard.nextInt();
int i;
for (i = 0; n > 0; i++) {
n /= 10;
for (i = 0; n > 0; i++) {
n /= 10;
System.out.println((n%100000) / 10000);
System.out.println((n%10000) / 1000);
System.out.println((n%1000) / 100);
System.out.println((n%100) / 10);
System.out.println(n%10);
}
System.out.println("Number of digits: " + i);
}
}
After removing this, the code seems to work as intended, and tells you that 545 does, in fact have 3 digits. Here is the revised code:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter a number: ");
int n = keyboard.nextInt();
int i;
for (i = 0; n > 0; i++) {
n /= 10;
System.out.println((n%100000) / 10000);
System.out.println((n%10000) / 1000);
System.out.println((n%1000) / 100);
System.out.println((n%100) / 10);
System.out.println(n%10);
}
System.out.println("Number of digits: " + i);
}
Seems like you trying to do the same task, by using arbitrary values. Instead try to incorporate some generic sort of an algorithm. Somethingy on the lines of this posted example:
public class CountDigits {
private void performTask () {
int number = 546;
int temp = number;
int digit = 0;
int counter = 1;
while ( temp != 0 ) {
digit = temp % 10;
System.out.println ( digit + " * " + getMultiplier ( counter ) + " = " + ( digit * getMultiplier ( counter ) ) );
++counter;
temp /= 10;
}
}
private int getMultiplier ( int power ) {
int value = 1;
for ( int i = 1; i < power; ++i ) {
value *= 10;
}
return value;
}
public static void main ( String[] args ) {
new CountDigits ().performTask ();
}
}
OUTPUT:
C:\Mine\java\bin>java CountDigits
9 * 1 = 9
1 * 10 = 10
1 * 100 = 100
1 * 1000 = 1000
C:\Mine\java\bin>java CountDigits
6 * 1 = 6
4 * 10 = 40
5 * 100 = 500
int n = 546;
for( int i = 0, dig = (int) Math.log10( n ) + 1; i < dig; ++i )
{
int mult = (int) Math.pow( 10, dig - i - 1 );
int a = (n / mult) % 10;
System.out.println( a + " * " + mult + " = " + (a * mult) );
}
Results in:
5 * 100 = 500
4 * 10 = 40
6 * 1 = 6
To get the number of digits in user entered value, you can get the value and check the length of the value after converting it to String. This will give you the exact length of the digit.
For example, if variable "uservalue" in the below snippet is user entered value, the output after executing the snippet, it prints the numberOfDigit as"3".
public static void main (String args[]){
int uservalue=546;
int numberOfDigit=0;
String userValueinStr=String.valueOf(uservalue);
numberOfDigit=userValueinStr.length();
System.out.println("Number of digits in user entered value is::"+numberOfDigit );
//Now as you got the no. of digits, you can go ahead and add the your logic of multiplication
}
int n = 546;
int exponent = (int) (Math.log10(n));
for (int i = exponent; i >= 0; i--) {
int displayNum = (n / (int) Math.pow(10, i)) * (int) Math.pow(10, i);
System.out.println(displayNum);
n = n - displayNum;
}
outputs
System.out﹕ 500
System.out﹕ 40
System.out﹕ 6

Why does this statement print this output?

Why does this print statement print 3 and not 1004 as the output?
int n = 2005;
for (int i = 0; i < 50; i++)
n = (n + 3) / 2;
System.out.print(n);
if I do this:
int n = 2005;
for (int i = 0; i < 50; i++)
System.out.println(n);
n = (n + 3) / 2;
System.out.print(n);
It prints 2005 for each iteration and 1004, for the last time.
If there was brackets (like below)
int n = 2005;
for (int i = 0; i < 50; i++){
System.out.println(n);
n = (n + 3) / 2;
}
System.out.print(n);
}
then it behaves like 2005
1004
503
253
128
65
34
18
10
6
4
3
3....3
Print n inside the for loop then you will got how this work.
int n = 2005;
for (int i = 0; i < 50; i++){
System.out.println(n);
n = (n + 3) / 2;
}
Without going into detail: You are more or less cutting n in half every time. Eventually n will approach 3. Then its (3 + 3) / 2 == 3. In fact, you would get there for most initial numbers given a long enough iteration.

Categories

Resources