简体   繁体   中英

how do i alternate from positive int and negative int in a number sequence

I am doing an assignment for university and I have to print out the first ten numbers of a number sequence which is 1, 2, 0, 3, -1, 4, -2.... I have worked out the rest of the sequence which is where you alternate adding a positive number and then a negative one for example to go from 1 to 2 you add the number one and then to go from 2 to 0 you add the number -2. But I cant quite get my head around how to alternate from positive to negative using just a simple while loop. I dont want this to be solved for me I just want for someone to tell me how I would alternate the positive and negative ints. Any help is appreciated thank you.

This reads like a straightforward arithmetic problem.

1 + 1 is 2.
2 - 2 is 0.
0 + 3 is 3.
3 - 4 is -1.
-1 + 5 is 4.

From there, the pattern is fairly straightforward - the addend (the second number you're adding) increments from 1 to 5, but it has alternating signs. The augend (the first number you're adding) starts at 1 but is the result of the previous sums.

Multiplying the addend by -1 in a loop would be a start; I leave this as an exercise for the reader (as the hard part - determining the algorithm - has been explained above).

Sorry for posting the code. The idea is to swap between the negative and positive multiplier after each step in while cycle.

int precision = 10;
int i = 0;
int lastNum = 1;
boolean switcher = false;
while (i++ <= precision) {
    System.out.println(lastNum);
    lastNum += (switcher = !switcher) ? i : -i;
}

 var precision = 10; var i = 0; var lastNum = 1; var switcher = false; while (i++ <= precision) { console.log(lastNum); lastNum += (switcher = !switcher) ? i : -i; } 

The Maths are :

f(x) = 1+x/2 if x is even

f(x) = (3-x)/2 if x is odd

So you can simply do this :

public static void main(String[] args){
    int desiredLength = 10;
    for (int i =1; i<=desiredLength; i++)
        System.out.println(i+" : "+myFunction(i);
}

public static int myFunction(int x){
    return (x%2==1?(3-x)/2:1+x/2);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM