Java Loop to go Through Numbers and Adding 5 - java

I am writing Java code that needs to print these numbers: "0 5 10 3 8 1 6 11 4 9 2 7" in that order. I am new to Java, and am not very good at Loops yet. I am finding the points of a 12 point star, starting at 0, and trying to find the points that need to be touched by a line to make the star..
How do I do a loop that starts at 0, and adds 5 to each number.. so 0 + 5 = 5, 5+5=10, 10+5=3 (this is where my problem is.. How do I make it go back from 11 to 0?
I know this might seem confusing... or it might be extremely easy.. but any help would be greatly appreciated.

Increment by 5 until you pass 60, display the result of modulo 12. Something like,
for (int i = 0; i < 60; i += 5) {
System.out.println(i % 12);
}

This is called modulus, and java has the modulo operator % which gives the remainder of integer division.
15 / 12 == 1
15 % 12 == 3
as
(15 / 12) * 12 + (15 % 12) == 15
See the wikipedia.
Of course in your case you could also do
n += 5;
if (n >= 12) {
n -= 12;
}
instead of using modulo:
n = (n + 5) % 12;

Just iterate from 0 to 12, multiplying your number by 5, and applying modulus 12:
for (int i = 0; i < 12; i++) {
System.out.println(i * 5 % 12);
}

I believe the operator you are looking for is the modulus operator. The modulus gives you the remainder from a division problem. In this case you are using 12 as the denominator.
0 + 5 % 12 = 5 (0, remainder 5)
5 + 5 % 12 = 10 (0, remainder 10)
10 + 5 % 12 = 3 (1, remainder 3)
15 + 5 % 12 = 8 (1, remainder 8)
20 + 5 % 12 = 1 (2, remainder 1)

try this :
for(int i=0; ; i = (i+5)%12){
System.out.println(i);
if(i==7)break;
}

Related

Is there a best approach to create four times 1 - 12 blocks through a loop

There is a loop that increments the counter 48 times to write certain values to an Excel file.
In the range 1 - 48, 4 blocks from 1 - 12 are to be written.
Expected example:
1 2 3 4 5 6 7 8 9 10 11 12 - 1 2 3 4 5 6 7 ... and so on (4 times).
I have tried different approaches, if/else, switch/case but here I have not come to any result.
My last approach is an if condition with the modolu operator.
for (int i = 1; i <= 48; i++) {
if (i % 12 != 0) {
for (int j = 1; j <= 12; j++) {
workBook.setNumber(HEADLINE_ROW, i + 6, j);
}
} else {
workBook.setNumber(HEADLINE_ROW, i + 6, 12);
}
}
But with this approach I get 12 12 12 12 and so on.
I recognize the error, but currently have no idea how to solve the problem. The part where data is written to the Excel file is rather unimportant. I am concerned with the logic.
I'm stuck in the logic here and can't get any further. Do you have any ideas or suggestions for improvement on how I can generate four 1 - 12 blocks side by side?
do something like that
python
for i in range(48):
index = i % 12 + 1
# do what ever you want here
print(index)
java
for(int i = 0; i < 48; i++) {
int index = i % 12 + 1;
// do something here
}
I think the pseudo code for what you want would be:
for (int i=1; i <= 48; i++) {
int j = i % 12 + 1; // 1 2 3 4 5 6 7 8 9 10 11 12 1 2 3 ...
// do something with i and (j + 1)
}
That is, work with the outer loop counter mod 12, which would give you the sequence 1, 2, ..., 12, four times.

Get the consecutive numbers whose sum matches with given number

I was going through a simple program that takes a number and finds the number of occurrences of consecutive numbers that matches with given number.
For example:
if input is 15, then the consecutive numbers that sum upto 15 are:
1,2,3,4,5
4,5,6
7,8
So the answer is 3 as we have 3 possibilities here.
When I was looking for a solution I found out below answer:
static long process(long input) {
long count = 0;
for (long j = 2; j < input/ 2; j++) {
long temp = (j * (j + 1)) / 2;
if (temp > input) {
break;
}
if ((input- temp) % j == 0) {
count++;
}
}
return count;
}
I am not able to understand how this solves the requirement because this program is using some formula which I am not able to understand properly, below are my doubts:
The for loop starts from 2, what is the reason for this?
long temp = (j * (j + 1)) / 2; What does this logic indicates? How is this helpful to solving the problem?
if ((num - temp) % j == 0) Also what does this indicate?
Please help me in understanding this solution.
I will try to explain this as simple as possible.
If input is 15, then the consecutive numbers that sum upto 15 are:
{1,2,3,4,5} -> 5 numbers
{4,5,6} -> 3 numbers
{7,8} -> 2 numbers
At worst case, this must be less than the Sum of 1st n natural numbers = (n*(n+1) /2.
So for a number 15, there can never be a combination of 6 consecutive numbers summing up to 15 as the sum of 1st 6 numbers =21 which is greater than 15.
Calculate temp: This is (j*(j+1))/2.
Take an example. Let input = 15. Let j =2.
temp = 2*3/2 = 3; #Meaning 1+2 =3
For a 2-number pair, let the 2 terms be 'a+1' and 'a+2'.(Because we know that the numbers are consecutive.)
Now, according to the question, the sum must add up to the number.
This means 2a+3 =15;
And if (15-3) is divisible by 2, 'a' can be found. a=6 -> a+1=7 and a+2=8
Similarly, let a+1 ,a+2 and a+3
a + 1 + a + 2 + a + 3 = 15
3a + 6 = 15
(15-6) must be divisible by 3.
Finally, for 5 consecutive numbers a+1,a+2,a+3,a+4,a+5 , we have
5a + 15 = 15;
(15-15) must be divisible by 5.
So, the count will be changed for j =2,3 and 5 when the input is 15
If the loop were to start from 1, then we would be counting 1 number set too -> {15} which is not needed
To summarize:
1) The for loop starts from 2, what is the reason for this?
We are not worried about 1-number set here.
2) long temp = (j * (j + 1)) / 2; What does this logic indicates? How is this helpful to solving the problem?
This is because of the sum of 1st n natural numbers property as I have
explained the above by taking a+1 and a+2 as 2 consecutive
numbers.
3) if ((num - temp) % j == 0) Also what does this indicate?
This indicates the logic that the input subtracted from the sum of 1st
j natural numbers must be divisible by j.
We need to find all as and ns, that for given b the following is true:
a + (a + 1) + (a + 2) + ... (a + (n - 1)) = b
The left side is an arithmetic progression and can be written as:
(a + (n - 1) / 2) * n = b (*)
To find the limit value of n, we know, that a > 0, so:
(1 + (n - 1) / 2) * n = n(n + 1) / 2 <= b
n(n + 1) <= 2b
n^2 + n + 1/4 <= 2b + 1/4
(n + 1/2)^2 <= 2b + 1/4
n <= sqrt(2b + 1/4) - 1/2
Now we can rewrite (*) to get formula for a:
a = b / n - (n - 1) / 2
Example for b = 15 and n = 3:
15 / 3 - (3 - 1) / 2 = 4 => 4 + 5 + 6 = 15
And now the code:
double b = 15;
for (double n = 2; n <= Math.ceil(Math.sqrt(2 * b + .25) - .5); n++) {
double candidate = b / n - (n - 1) / 2;
if (candidate == (int) candidate) {
System.out.println("" + candidate + IntStream.range(1, (int) n).mapToObj(i -> " + " + (candidate + i)).reduce((s1, s2) -> s1 + s2).get() + " = " + b);
}
}
The result is:
7.0 + 8.0 = 15.0
4.0 + 5.0 + 6.0 = 15.0
1.0 + 2.0 + 3.0 + 4.0 + 5.0 = 15.0
We are looking for consecutive numbers that sum up to the given number.
It's quite obvious that there could be at most one series with a given length, so basically we are looking for those values witch could be the length of such a series.
variable 'j' is the tested length. It starts from 2 because the series must be at least 2 long.
variable 'temp' is the sum of a arithmetic progression from 1 to 'j'.
If there is a proper series then let X the first element. In this case 'input' = j*(X-1) + temp.
(So if temp> input then we finished)
At the last line it checks if there is an integer solution of the equation. If there is, then increase the counter, because there is a series with j element which is a solution.
Actually the solution is wrong, because it won't find solution if input = 3. (It will terminate immediately.) the cycle should be:
for(long j=2;;j++)
The other condition terminates the cycle faster anyway.
NB: loop is starting from 2 because=> (1*(1+1))/2 == 1, which doesn't make sense, i.e, it doesn't effect on the progress;
let, k = 21;
so loop will iterate upto (k/2) => 10 times;
temp = (j*(j+1))/2 => which is, 3 when j =2, 6 when j = 3, and so on (it calculates sum of N natural numbers)
temp > k => will break the loop because, we don't need to iterate the loop when we got 'sum' which is more than 'K'
((k-temp)%j) == 0 => it is basically true when the input subtracted from the sum of first j natural numbers are be divisible by j, if so then increment the count to get total numbers of such equation!
public static long process(long input) {
long count = 0, rest_of_sum;
for (long length = 2; length < input / 2; length++) {
long partial_sum = (length * (length + 1)) / 2;
if (partial_sum > input) {
break;
}
rest_of_sum = input - partial_sum
if (rest_of_sum % length == 0)
count++;
}
return count;
}
input - given input number here it is 15
length - consecutive numbers length this is at-least 2 at max input/2
partial_sum = sum of numbers from 1 to length (which is a*(a+1)/2 for 1 to a numbers) assume this is a partial sequence
rest_of_sum = indicates the balance left in input
if rest of sum is multiple of length meaning is that we can add (rest_of_sum/length) to our partial sequence
lets call (rest_of_sum/length) as k
this only means we can build a sequence here that sums up to our input number
starting with (k+1) , (k+2), ... (k+length)
this can validated now
(k+1) + (k+2) + ... (k+length)
we can reduce this as k+k+k+.. length times + (1+2+3..length)
can be reduced as => k* length + partial_sum
can be reduced as => input (since we verified this now)
So idea here is to increment count every-time we find a length which satisfies this case here
If you put this tweak in it may fix code. I have not extensively tested it. It's an odd one but it puts the code through an extra iteration to fix the early miscalculations. Even 1/20000 would work! Had this been done with floats that got rounded down and 1 added to them I think that would have worked too:
for (long j = 2; j < input+ (1/2); j++) {
In essence you need to only know one formula:
The sum of the numbers m..n (or m to n) (and where n>m in code)
This is ((n-m+1)*(n+m))/2
As I have commented already the code in the original question was bugged.
See here.
Trying feeding it 3. That has 1 occurrence of the consecutive numbers 1,2. It yields 0.
Or 5. That has 2,3 - should yield 1 too - gives 0.
Or 6. This has 1,2,3 - should yield 1 too - gives 0.
In your original code, temp or (j * (j + 1)) / 2 represented the sum of the numbers 1 to j.
1 2 3 4 5
5 4 3 2 1
=======
6 6 6 6 6 => (5 x 6) /2 => 30/2 => 15
As I have shown in the code below - use System.out.println(); to spew out debugging info.
If you want to perfect it make sure m and n's upper limits are half i, and i+1 respectively, rounding down if odd. e.g: (i=15 -> m=7 & n=8)
The code:
class Playground {
private static class CountRes {
String ranges;
long count;
CountRes(String ranges, long count) {
this.ranges = ranges;
this.count = count;
}
String getRanges() {
return this.ranges;
}
long getCount() {
return this.count;
}
}
static long sumMtoN(long m, long n) {
return ((n-m+1)* (n+m))/2;
}
static Playground.CountRes countConsecutiveSums(long i, boolean d) {
long count = 0;
StringBuilder res = new StringBuilder("[");
for (long m = 1; m< 10; m++) {
for (long n = m+1; n<=10; n++) {
long r = Playground.sumMtoN(m,n);
if (d) {
System.out.println(String.format("%d..%d %d",m,n, r));
}
if (i == r) {
count++;
StringBuilder s = new StringBuilder(String.format("[%d..%d], ",m,n));
res.append(s);
}
}
}
if (res.length() > 2) {
res = new StringBuilder(res.substring(0,res.length()-2));
}
res.append("]");
return new CountRes(res.toString(), count);
}
public static void main(String[ ] args) {
Playground.CountRes o = countConsecutiveSums(3, true);
for (long i=3; i<=15; i++) {
o = Playground.countConsecutiveSums(i,false);
System.out.println(String.format("i: %d Count: %d Instances: %s", i, o.getCount(), o.getRanges()));
}
}
}
You can try running it here
The output:
1..2 3
1..3 6
1..4 10
1..5 15
1..6 21
1..7 28
1..8 36
1..9 45
1..10 55
2..3 5
2..4 9
2..5 14
2..6 20
2..7 27
2..8 35
2..9 44
2..10 54
3..4 7
3..5 12
3..6 18
3..7 25
3..8 33
3..9 42
3..10 52
4..5 9
4..6 15
4..7 22
4..8 30
4..9 39
4..10 49
5..6 11
5..7 18
5..8 26
5..9 35
5..10 45
6..7 13
6..8 21
6..9 30
6..10 40
7..8 15
7..9 24
7..10 34
8..9 17
8..10 27
9..10 19
i: 3 Count: 1 Instances: [[1..2]]
i: 4 Count: 0 Instances: []
i: 5 Count: 1 Instances: [[2..3]]
i: 6 Count: 1 Instances: [[1..3]]
i: 7 Count: 1 Instances: [[3..4]]
i: 8 Count: 0 Instances: []
i: 9 Count: 2 Instances: [[2..4], [4..5]]
i: 10 Count: 1 Instances: [[1..4]]
i: 11 Count: 1 Instances: [[5..6]]
i: 12 Count: 1 Instances: [[3..5]]
i: 13 Count: 1 Instances: [[6..7]]
i: 14 Count: 1 Instances: [[2..5]]
i: 15 Count: 3 Instances: [[1..5], [4..6], [7..8]]

What does the percentage symbol (%) mean? [duplicate]

This question already has answers here:
Understanding The Modulus Operator %
(10 answers)
Closed 5 years ago.
I ran into some code containing the % symbol inside the array argument.
What does it mean and how does it work?
Example:
String[] name = { "a", "b", "c", "d" };
System.out.println(name[4 % name.length]);
System.out.println(name[7 % name.length]);
System.out.println(name[50 % name.length]);
Output:
a
d
c
That's the remainder operator, it gives the remainder of integer division. For instance, 3 % 2 is 1 because the remainder of 3 / 2 is 1.
It's being used there to keep a value in range: If name.length is less than 4, 7, or 50, the result of % name.length on those values is a value that's in the range 0 to name.length - 1.
So that code picks entries from the array reliably, even when the numbers (4, 7, or 50) are out of range. 4 % 4 is 0, 7 % 4 is 3, 50 % 4 is 2. All of those are valid array indexes for name.
Complete example (live copy):
class Example
{
public static void main (String[] args) throws java.lang.Exception
{
String[] name = { "a" , "b" , "c" , "d"};
int n;
n = 4 % name.length;
System.out.println(" 4 % 4 is " + n + ": " + name[n]);
n = 7 % name.length;
System.out.println(" 7 % 4 is " + n + ": " + name[n]);
n = 50 % name.length;
System.out.println("50 % 4 is " + n + ": " + name[n]);
}
}
Output:
4 % 4 is 0: a
7 % 4 is 3: d
50 % 4 is 2: c
Simple: this is the modulo, or to be precise the remainder operator.
This has nothing to do with arrays per se. It is just a numerical computation on the value that gets used to compute the array index.

Project Euler #5 in Java: stuck in the end of program

I am trying to get the smallest positive number that is evenly divisible by all of the numbers from 1 to 20. But somehow I am stuck in the end of the program. My answer is coming 40 which is wrong. Here is my code:
public class Lessons {
public static void main(String[] args) {
int n;
int s = 0;
for (n = 21; n > 0; n++)
{
for (int m = 1; m <= 20; m++)
{
s = n % m;
}
if (s == 0)
{
System.out.println(n);
break;
}
}
}
}
Any helps???
You're effectively only ever checking whether n%20 == 0. This loop:
for (int m = 1; m <= 20; m++) {
s = n % m;
}
does run for m from 1 to 20, but you always overwrite s and never do anything with the value before resetting it the next time through the loop. You need to check the result of n % m for each iteration of the loop, perhaps like:
for (n = 21; n > 0; n++) {
bool divisibleByAll = true;
for (int m = 1; m <= 20; m++) {
s = n % m;
if(s != 0) {
divisibleByAll = false;
break; //don't bother checking the rest
}
}
if (divisibleByAll) {
System.out.println(n);
break;
}
}
another option with brute force and modulo rest-classification
this problem can be solved with a simple common modulo rest class characteristrics.
look at the numbers from 1 to 20 and divide it into two groups and find some unique common attributes between them.
1 2 3 4 5 6 7 8 9 10
we are building division with the same reminder members
1 divides all
2 divide 4,8 -->>8 important
3 divide 6,9 but 6 doesnt divide 9 evenly--> 6,9
5 divide 10-->> 10 important
that leaves us with 6,7,8,9,10 to check if there is any number from 1 that can divide this with rest 0.
the trick is if 2,4,8 divides a number let say 16 with the same reminder then we dont have to check if 2,4 divides 16, we check only 8.
11 12 13 14 15 16 17 18 19 20
hier were can do the same from about with factors of the numbers from above and we will be left with
11 12 13 14 15 16 17 18 19 20
NB: we know that the last number that has to divide the number is 20,
so that mean either the solution will be a number ending with 0 or is
one of the factors of 20, so we build factors of 20 and check if 11 12
13 14 15 16 17 18 19 can divide it then we are done.
int start = 20;
while (start % 11 != 0 || start % 12 != 0 | start % 13 != 0 || start % 14 != 0 ||
start % 15 != 0 || start % 16 != 0 || start % 17 != 0 || start % 18 != 0 || start % 19 != 0 )
{
start += 20;
}
System.out.println("The smallest number is: "+start);
The same idea applies analog to the first deduction i made to make the
problem seems smaller.
//smallest number divisible by all numbers from 1 to 10
int a = 10;
while (a % 6 != 0 || a % 7 != 0 | a % 8 != 0 || a % 9 != 0 )
{
a += 10;
}
System.out.println("The smallest number is: "+a);
//smallest number divisible by all numbers from 1 to 5
int i = 5;
while (i % 3 != 0 || i % 4 != 0)
{
i += 5;
}
System.out.println("The smallest number is: "+ i);
long startTime = System.currentTimeMillis();
for ( int i = 2520; ; i += 2520 ){
if ( i % 11 == 0 &&
i % 12 == 0 &&
i % 13 == 0 &&
i % 14 == 0 &&
i % 15 == 0 &&
i % 16 == 0 &&
i % 17 == 0 &&
i % 18 == 0 &&
i % 19 == 0 &&
i % 20 == 0 ){
long stopTime = System.currentTimeMillis();
System.out.println("Answer: " + i + "\nIt took "+(stopTime - startTime) + " milliseconds");
break;
}
}
This takes 1 - 2 milliseconds on average. I know its a lame ass solution but hey it works.

Printing numbers divisible by 2 but not 3?

for (int i=n1; i < n2; i++){
if (i % 2 == 0){
System.out.println(i);
}
}
This code prints out all the numbers between n1 and n2 (which are generated randomly) that are both divisible by 2 and 3, but i only want to print out the numbers that are divisible by 2. How do i do this?
You're literally halfway there.
You need a second condition in which you mandate that the number is not divisible by 3. It would look something like this:
!(i % 3 == 0)
Now, you need a boolean operator to only return true if both conditions are true. That, I'll leave as an exercise to the reader.
(Others already gave the correct answer, but I will try to explain it a bit more naturally)
For computers, you need to write a sentence in a manner they can understand. You need to convert logical sentences like "divise by 2 but not by 3" to a bit more basic version, using only the words "not", "and" and "or". In your specific case, you want to say the numbers that are divisible by 2 AND NOT divisible by 3
As you already noticed, N%X!=0 is a (ugly) way to write N is divisible by X. In Java, we use ! to say not and && to say and.
This way, (N is divisible by 2) AND NOT (N is divisible by 3) can be written (N % 2 == 0) && !(N % 3 == 0). But we also have the X not equal Y operator (X!=Y), which is equivalent to NOT (X equal Y) but easier to understand, resulting in this code:
if ((i % 2 == 0) && (i % 3 != 0)) {
System.out.println(i);
}
I am use bit operator to for best performance (if (i & 1) == 0, i is even number). Because even number in binary always have the end is 0 digit.
public class Example {
public static void main(String[] args) {
int n1 = 0;
int n2 = 100;
for (int i = n1; i < n2; i++) {
if (((i & 1) == 0)) {
if (i % 3 != 0) {
System.out.print(i + " ");
}
}
}
}
}
// Result:
// 2 4 8 10 14 16 20 22 26 28 32 34 38 40 44 46 50 52 56 58 62 64 68 70 74 76 80 82 86 88 92 94 98
There are better way, for example 3534 % 3 == 0, we have: sum of all digits (3 + 5 + 3 + 4) = 15, and 15 % 3 == 0... Let's code follow this.
When n is big, for example n2 = 99999999999999 , use sum of all digits is (9+9+9+9+9+9+9+9+9+9+9+9+9+9) % 3 == 0, and bit operator is very sense :)
A more efficient solution is to print the even numbers (every second) which are not multiples of 3, (every third number)
for (int i = 2; i < n; i += 6) {
System.out.println(i);
if (i + 2 < n)
System.out.println(i + 2);
}
The modulus operation is expensive and this will print two numbers with each loop instead of two numbers every six loops.
Use the logical and comparison operator &&
for (int i=n1; i < n2; i++){
if (i % 2 == 0 && i % 3 != 0) {
System.out.println(i);
}
}
Your if conditional now asks if "i is divisible by 2 AND is not divisible by 3"

Categories