I have an assignment of which a part is to generate n random numbers between 0-99 inclusive in a 1d array, where the user enters n. Now, I have to print out those numbers formatted like this:
What is your number? 22 //user entered
1 2 3 4 5 6 7 8 9 10
----random numbers here---------
11 12 13 14 15 16 17 18 19 20
-----random numbers here--------
21 22
---two random numbers here---
Using those numbers, I have find lots of other things, (like min, max, median, outliers, etc.) and I was able to do so. However, I wasn't able to actually print it out in the format shown above, with no more than 10 numbers in one row.
Edit: Hello, I managed to figure it out, here's how I did it:
int counter = 0;
int count2 = 0;
int count3 = 0;
int add = 0;
int idx = 1;
int idx2 = 0;
if (nums > 10)
{
count3 = 10;
count2 = 10;
}
else
{
count3 = nums;
count2 = nums;
}
if (nums%10 == 0) add = 0;
else add = 1;
for (int i = 0; i < nums/10 + add; i++)
{
for (int j = 0; j < count3; j++)
{
System.out.print(idx + "\t");
idx++;
}
System.out.println();
for (int k = 0; k < count2; k++)
{
System.out.print(numbers[idx2] + "\t");
idx2++;
counter++;
}
System.out.println("\n");
if (nums-counter > 10)
{
count3 = 10;
count2 = 10;
}
else
{
count3 = nums-counter;
count2 = nums-counter;
}
}
Thank you to everyone who helped! Also, please let me know if you find a way to shorten what I have done above.
*above, nums was the number of numbers the user entered
I'd use a for-loop to make an array of arrays: and then formatting the lines using those values:
var arr_random_n = [1,2,3,4,5,6,7,8,9,0,1,2,3,6,4,6,7,4,7,3,1,5,7,9,5,3,2,54,6,8,5,2];
var organized_arr = [];
var idx = 0
for(var i = 0; i < arr.length; i+=10){
organized_arr[idx] = arr.slice(i, i+10); //getting values in groups of 10
idx+=1 //this variable represents the idx of the larger array
}
Now organized_arr has an array of arrays, where each array in index i contains the values to be printed in line i.
There's probably more concise ways of doing this. but this is very intuitive.
Let me know of any improvements.
Something like this might be what you're looking for.
private static void printLine(String msg)
{
System.out.println("\r\n== " + msg + " ==\r\n");
}
private static void printLine(int numDisplayed)
{
printLine(numDisplayed + " above");
}
public static void test(int total)
{
int[] arr = new int[total];
// Fill our array with random values
for (int i = 0; i < total; i++)
arr[i] = (int)(Math.random() * 100);
for (int i = 0; i < total; i++)
{
System.out.print(arr[i] + " ");
// Check if 10th value on the line, if so, display line break
// ** UNLESS it's also the last value - in that case, don't bother, special handling for that
if (i % 10 == 9 && i != total - 1)
printLine("Random Numbers");
}
// Display number of displayed elements above the last line
if (total < 10 || total % 10 != 0)
printLine(total % 10);
else
printLine(10);
}
To print 10 indexes on a line then those elements of an array, use two String variables to build the lines, then print them in two nested loops:
for (int i = 0; i < array.length; i += 10) {
String indexes = "", elements = "";
for (int j = 0; j < 10 && i * 10 + j < array.length; j++) {
int index = i * 10 + j;
indexes += (index + 1) + " "; // one-based as per example in question
elements += array[index] + " ";
}
System.out.println(indexes);
System.out.println(elements);
}
I'm trying to write a program using Java, that (outputs) the following pattern depending on an input (integer) (n = 5):
0********1
23******45
678****901
2345678901
As you noticed:
input(3) represent 3 rows
single row digits (n * 2)
Digits should start from 0 to 9 and then repeat until the pattern is fully done
First row should have only 2 numbers (start 0 end 1)
(*) will be in between
Next row should have 4 numbers (start 23 end 45) and so on
How can this program written?
Here is my code:
import java.util.Scanner;
public class b_test_2 {
public static void main (String arug[]) {
String star = "*";
int star_count, digit = 0;
Scanner sc = new Scanner(System.in);
System.out.print("Please type a number (int)");
int n = sc.nextInt();
while (n != 0){
star_count = n * 2 - 2;
for (int i=0; i<n; i++) {
System.out.print(star);
i = i + 1;
}
String stars = star;
n = n - 1;
for (int i2=0; i2<n; i2++) {
System.out.print(star);
i2 = i2 + 1;
int x = 0;
x = digit;
x = x + 1;
if (x == 10){
x = 0;
System.out.print(digit + stars + digit);
}
}
}
}
}
There are any parts missing in your code, but you also seem to make it more complicated than it is.
To illustrate, and hopefully help you to go in the right direction, here is compact code to do it. Do not hand in this code unless you fully understand how it works.
static void printPattern(int n) {
for (int row = 1, digit = 0; row <= n; row++) {
for (int i = 0; i < row; i++, digit = (digit + 1) % 10)
System.out.print(digit);
for (int i = (n - row) * 2; i > 0; i--)
System.out.print('*');
for (int i = 0; i < row; i++, digit = (digit + 1) % 10)
System.out.print(digit);
System.out.println();
}
}
Test
printPattern(4);
Output
0******1
23****45
678**901
23456789
I case you haven't learned it yet, the % operator calculates the remainder after division.
Input
The input begins with the number t of test cases in a single line (t<=10). In each of the next t lines there are two numbers m and n (1 <= m <= n <= 1000000000, n-m<=100000) separated by a space.
Output
For every test case print all prime numbers p such that m <= p <= n, one number per line, test cases separated by an empty line.
Example
Input:
2
1 10
3 5
Output:
2
3
5
7
3
5
As i declare it. I solved this question but i am trying to upload the solution for one site but i am getting time limit exceeded.I didn't figure it out to optimizing.
Could anyone help? Thank you.
Scanner s = new Scanner(System.in);
int t = s.nextInt();
int flag = 0;
int arr[][] = new int[t][2];
for (int i = 0; i < t; i++) {
for (int j = 0; j < 2; j++) {
arr[i][j] = s.nextInt();
}
}
for (int a = 0; a < t; a++) {
for (int b = arr[a][0]; b <= arr[a][1]; b++) {
if (b < 2) {
b = 2;
}
for (int c = 2; c < b; c++) {
if (b % c == 0) {
flag = 1;
break;
}
}
if (flag == 0) {
System.out.println(b);
} else {
flag = 0;
}
}
}
Your code looks good, but have one problem at for (int c = 2; c < b; c++).
The simplest primality test is trial division: Given an input number n, check whether any prime integer m from 2 to √n evenly divides n (the division leaves no remainder). If n is divisible by any m then n is composite, otherwise, it is prime.
For example, to test the primality of 100 by trial division, consider all the integer divisors of 100:
2, 4, 5, 10, 20, 25, 50
The largest factor is 100/2 = 50. This is true for all n: all divisors are less than or equal to n/2. Inspecting the divisors, it is determined that some of them are redundant. The list of divisors may be written as:
100 = 2 × 50 = 4 × 25 = 5 × 20 = 10 × 10 = 20 × 5 = 25 × 4 = 50 × 2
which demonstrates the redundancy. Once the divisor 10 is tested, which is √100, the first divisor is simply the dividend of a previous divisor. Therefore, testing divisors greater than √n can be eliminated. All the even numbers are greater than 2 can also be eliminated, since if an even number can divide so can 2.
Source Wikipedia Primalty test.
SO a small modification in your code can improve running time many folds.
Scanner s = new Scanner(System.in);
int t = s.nextInt();
int flag = 0;
int arr[][] = new int[t][2];
for (int i = 0; i < t; i++) {
for (int j = 0; j < 2; j++) {
arr[i][j] = s.nextInt();
}
}
for (int a = 0; a < t; a++) {
for (int b = arr[a][0]; b <= arr[a][1]; b++) {
if (b < 2) {
b = 2;
}
for (int c = 2; c*c <= b; c++) {
if (b % c == 0) {
flag = 1;
break;
}
}
if (flag == 0) {
System.out.println(b);
} else {
flag = 0;
}
}
}
I am having a problem trying to subtract with carrys in Java.
public BigInt add(BigInt o) {
int carry = 0;
int max = n.length > o.n.length ? n.length : o.n.length;
int[] result = new int[max+1];
for (int i = 0; i <= max; ++i) {
int top = i < n.length ? n[i] : 0;
int bot = i < o.n.length ? o.n[i] : 0;
result[i] = (top + bot + carry) % 10;
carry = (top + bot + carry) / 10;
}
return new BigInt(trim(result));
}
public BigInt sub(BigInt o) {
int carry = 0;
int max = n.length > o.n.length ? n.length : o.n.length;
int[] result = new int[max+1];
for (int i = 0; i <= max; ++i) {
int top = i < n.length ? n[i] : 0;
int bot = i < o.n.length ? o.n[i] : 0;
carry = (top + bot + carry) / 10;
result[i] = (10 + top - bot - carry) % 10;
}
return new BigInt(trim(result));
}
I don't know what I'm doing wrong? My addition class works perfect but subtraction is giving me a weird answer. Lets say if I subtract 5943-3952 ill get 2091. When we know the answer is 1991. All my answers are only incorrect in the first 2 digits. Help!!!!
There is a lot wrong with your code, but first something that will give you the desired result:
public BigInt sub(BigInt o)
{
int carry = 0;
int max = n.length > o.n.length ? n.length : o.n.length;
int[] result = new int[max+1];
for (int i = 0; i <= max; ++i)
{
int top = i < n.length ? n[i] : 0;
int bot = i < o.n.length ? o.n[i] : 0;
int res = top - bot - carry;
result[i] = (10 + res) % 10;
carry = res < 0 ? 1 : 0;
}
return new BigInt(trim(result));
}
Note, however, that you don't account for the fact that the left operand could be smaller than the right, so you would get a negative result. In your representation of a BigInt as an array of "digits", there doesn't seem to be a way to represent negative values. If there is, I don't see it.
If you have negative values too, there are four scenarios:
positive - positive: always subtract lowest value from highest (always 38 - 17 and never 17 - 38), adjust sign accordingly (e.g. 17 - 38 => 38 - 17 = 21, now adjust sign because first is smallest: result -21). Note that you need a function to compare the magnitudes (i.e. the values in the array regardless of the sign).
positive - negative: add the magnitudes (arrays), sign is positive (e.g. 17 - (-38) = 17 + 38 = 55.
negative - positive: add the magnitudes, sign is negative. (e.g. -17 - (+38) = -17 - 38 = -(17 + 38) = -55.
negative - negative: as the first scenario, adjust sign accordingly.
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 );
}
}