I keep getting java.lang.ArrayIndexOutOfBoundsException: 500 - java

I keep getting an error that the array is out of bounds and I can't figure out what is wrong.
int[] oddArray = new int[500];//holds all the odd numbers
int[] primeArray = new int[500];//holds all the prime numbers
int[] modArray = new int[500];//holds all the mod values
int remainder, p = 0, x = 0;
//fills up the oddArray & modArray
for(int n = 0; n < 500; n++)
{
oddArray[n] = (n * 2) + 1;
modArray[n] = (n* 2) + 1;
}
for(int i = 0; i < 500; i++)
{
//finds prime numbers
for(int n = 0 ; n < 500; n++)
{
//divides the odd numbers by the current mod value
remainder = oddArray[n] % modArray[x];
//if remainder is not 0 it will place a value in prime array
if(remainder != 0)
{
primeArray[p] = oddArray[n];
p++;
}
}
//prints out list of odds/mod/and primes side by side
System.out.println(oddArray[i] + " | " + modArray[i] + " | " + primeArray[p]);
++x;
}
This is the error code
1 | 1 | 0
3 | 3 | 0
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 500
at projectprime_v1.ProjectPrime_V1.main(ProjectPrime_V1.java:41)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)

You are never resetting p, so eventually it will exceed 499, and cause the exception. Make sure that inside your loop to write p = 0; to reset it. The same goes for x
Hope this helps!

Related

how to print out the nth row of pascal's triangle using 1d arrays in java

it should be a program that will print the row of the pascal's triangle depending on the user input, so if the user enters 4, the output will be: 1 3 3 1. i've figured out how to print out the entire pascal's triangle, but i'm not sure how to adjust it so that it only prints out the nth row.
public class PascalTriangle
{
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Please enter a number.");
int num = input.nextInt();
input.nextLine();
int x=1;
int y=0;
int[] pascal = new int[num];
int[] pascalTemp = new int[num];
pascal[0] = 1;
pascal[1] = 1;
for(int i=0; i<num; i++)
{
for(int j=0; j<=i; j++)
{
if(i==0)
System.out.print("1");
else
{
if(j==0 || j==i)
System.out.print("1 ");
else
{
pascalTemp[x] = pascal[y] + pascal[y+1];
System.out.print(pascalTemp[x]+ " ");
x++;
y++;
}
}
}
System.out.println();
pascalTemp[x] = 1;
if(i>1)
{
y=0;
pascal[y]=1;
for(x=1, y=1; y<=i; x++, y++)
pascal[y] = pascalTemp[x];
x=1;
y=0;
}
}
}
}
The r-th number of the n-th line (r = 0, 1, 2, 3, ...) is (n - 1)Cr = (n - 1)! / (r! * (n - 1 - r)!) . (n - 1)C0 is always 1. And (n - 1)C(r + 1) can be obtained from (n - 1)Cr. For example, when n = 4, it becomes as follows.
3C0 = 1 = 1
3C1 = 3C0 * 3 / 1 = 3
3C2 = 3C1 * 2 / 2 = 3
3C3 = 3C2 * 1 / 3 = 1
Multiplying numbers decrease by 1 and dividing numbers increase by 1.
If you program this, it will be as follows.
static void pascalNthRow(int n) {
for (int p = 1, m = n - 1, d = 1; d <= n; p = p * m / d, --m, ++d)
System.out.print(p + " ");
System.out.println();
}
and
pascalNthRow(3);
pascalNthRow(4);
pascalNthRow(5);
output
1 2 1
1 3 3 1
1 4 6 4 1

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.

Drawing a diamond of numbers in a 2d array Java

I've been solving some coding questions to get myself prepared for a coding interview, and found out a question that seemed kind of puzzling. I solved the question after spending some time on it; however, the code looks hardcoded and has no style. So, I was wondering if I could get some feedbacks on styling the code, or perhaps getting an better idea of approaching the problem.
The question basically asks you to draw a diamond of numbers with a pattern in 2d array.
It gives a coordinate of 'x' and range of x. From the x, the numbers spread one by one until the range. So, there are 4 different inputs, N (the size of an array), X, Y (the coordinate of 'x' as (rows, cols)), and R (range).
If they were given a size of 8, coordinate of (4,5) with a range of 3, the result would be like,
0 0 0 0 3 0 0 0
0 0 0 3 2 3 0 0
0 0 3 2 1 2 3 0
0 3 2 1 x 1 2 3
0 0 3 2 1 2 3 0
0 0 0 3 2 3 0 0
0 0 0 0 3 0 0 0
0 0 0 0 0 0 0 0
And the below is what I have,
int n = sc.nextInt();
char[][] arr = new char[n][n];
int r = sc.nextInt() - 1;
int c = sc.nextInt() - 1;
int range = sc.nextInt();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
arr[i][j] = '0';
}
}
arr[r][c] = 'x';
int num = 1;
for (int i = 0; i < range; i++) {
//Cross
if (c-num > -1) {
arr[r][c - num] = (char) (num + '0');
}
if (c+num < n) {
arr[r][c + num] = (char) (num + '0');
}
if (r-num > -1) {
arr[r - num][c] = (char) (num + '0');
}
if (r+num < n) {
arr[r + num][c] = (char) (num + '0');
}
//Diagonal
if (i > 0) {
int sum = num - 1, delta = 1;
while (sum != 0) {
if (r-sum > -1 && c+delta < n) {
arr[r - sum][c + delta] = (char) (num + '0');
}
sum--;
delta++;
}
sum = num - 1; delta = 1;
while (sum != 0) {
if (r+sum < n && c-delta > -1) {
arr[r + sum][c - delta] = (char) (num + '0');
}
sum--;
delta++;
}
sum = num - 1; delta = 1;
while (sum != 0) {
if (r-sum > -1 && c-delta > -1) {
arr[r - sum][c - delta] = (char) (num + '0');
}
sum--;
delta++;
}
sum = num - 1; delta = 1;
while (sum != 0) {
if (r+sum < n && c+delta > -1) {
arr[r + sum][c + delta] = (char) (num + '0');
}
sum--;
delta++;
}
}
num++;
}
I could not figure out any other way to take care of the diagonal numbers other than using four different while-loops. I would appreciate any kind of feedback. Thanks in advance!
You can just loop over the array once, and set the values based on the relative distance of the current location (i, j) to the fixed coordinate (x, j).
Your code could look like this:
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
// variables
int n = 8;
int x = 4 - 1; // coordinates are one-based
int y = 5 - 1; // coordinates are one-based
int r = 3;
char[][] array = new char[n][n];
// logic
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
int dist = Math.abs(x - i) + Math.abs(y - j); // calculate distance
if(dist == 0) { // at x,y
array[i][j] = 'x';
} else if (dist <= r) { // distance to x,y is within range
array[i][j] = (char) (dist + '0');
} else { // distance to x,y is outside of range
array[i][j] = '0';
}
}
}
// dump output
System.out.println(Arrays.deepToString(array)
.replace("], ", "]\n")
.replace("[", "")
.replace("]", "")
.replace(", ", " "));
}
}
Which yields the following output:
0 0 0 0 3 0 0 0
0 0 0 3 2 3 0 0
0 0 3 2 1 2 3 0
0 3 2 1 x 1 2 3
0 0 3 2 1 2 3 0
0 0 0 3 2 3 0 0
0 0 0 0 3 0 0 0
0 0 0 0 0 0 0 0
If you want to be even more concise, you can replace the branched if… else if… else statement with ternary operators:
array[i][j] = dist == 0 ? 'x' : dist <= r ? (char) (dist + '0') : '0';
Here's a fairly compact method. On each iteration i we fill a single-character wide i+1 by i+1 diamond-shaped ring, centered on (row, col), with value i. To avoid filling the interior of the diamond we check that the manhattan distance to (row, col) is equal to i - this is only true for cells on the boundary of the diamond.
static char[][] buildDiamond(int n, int row, int col, int range)
{
char[][] arr = new char[n][n];
for(char[] a : arr) Arrays.fill(a, '0');
arr[row][col] = 'x';
for(int i=1; i<=range; i++)
for(int j=0; j<=i; j++)
for(int k=0; k<=i; k++)
if(Math.abs(k-j) + Math.abs(k+j-i) == i)
arr[row+k-j][col+k+j-i] += i;
return arr;
}
Test:
public static void main(String[] args)
{
for(char[] a : buildDiamond(7, 3, 3, 3))
System.out.println(new String(a).replaceAll(".", "$0 "));
}
Output:
0 0 0 3 0 0 0
0 0 3 2 3 0 0
0 3 2 1 2 3 0
3 2 1 x 1 2 3
0 3 2 1 2 3 0
0 0 3 2 3 0 0
0 0 0 3 0 0 0
You can try using floodfill, although depending on your level it might be a bit far.
https://en.wikipedia.org/wiki/Flood_fill
EDIT: Robby Cornelissen's code looks much cleaner and simpler than mine so you should probably check out his. However, floodfill is a pretty important concept for later on so might as well check it out.
The article is pretty long, but the GIF in the article is the most important part.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class test {
public static void main(String[] args) throws IOException {
//Get inputs (I used BufferedReader, Scanner works fine as well)
//My inputs are formatted as 'N X Y R' (ex. '8 4 5 3')
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine(), " ");
int N = Integer.parseInt(st.nextToken());
int R = Integer.parseInt(st.nextToken()) - 1;
int C = Integer.parseInt(st.nextToken()) - 1;
int range = Integer.parseInt(st.nextToken());
char[][] arr = new char[N][N];
//Make everything in array '0'
for (int i = 0; i < N; i++) {
Arrays.fill(arr[i], '0');
}
//Floodfill using BFS
//FYI: this BFS is iterative, not recursive
Queue<int[]> q = new LinkedList<>();
q.add(new int[]{0, R, C});
while (!q.isEmpty()) {
int[] current = q.remove();
if (arr[current[1]][current[2]] == '0' && current[0] <= range) {
arr[current[1]][current[2]] = (current[0]+"").charAt(0);
if(current[1]+1 < N) q.add(new int[]{current[0]+1, current[1]+1, current[2]});
if(current[1]-1>= 0) q.add(new int[]{current[0]+1, current[1]-1, current[2]});
if(current[2]+1 < N) q.add(new int[]{current[0]+1, current[1], current[2]+1});
if(current[2]-1>= 0) q.add(new int[]{current[0]+1, current[1], current[2]-1});
}
}
arr[R][C] = 'x';
//Print out the final grid
for (int i = 0; i < N; i++) {
for (int j = 0; j< N; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
}

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.

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

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 );
}
}

Categories

Resources