Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<iostream>
- using namespace std;
- void spiral(int n){
- int last_x, last_y;
- // (dx, dy) is a vector - direction in which we move right now
- int dx = 1;
- int dy = 0;
- // length of current segment
- int segment_length = 1;
- // current position (x, y) and how much of current segment we passed
- int x = 0;
- int y = 0;
- int segment_passed = 0;
- for (int k = 0; k < n; ++k) {
- // make a step, add 'direction' vector (dx, dy) to current position (x, y)
- x += dx;
- y += dy;
- ++segment_passed;
- //save last result of x and y to print
- last_x = x;
- last_y = y;
- if (segment_passed == segment_length) {
- // done with current segment
- segment_passed = 0;
- // 'rotate' directions
- int buffer = dx;
- dx = -dy;
- dy = buffer;
- // increase segment length if necessary
- if (dy == 0) {
- ++segment_length;
- }
- }
- }
- cout << last_x << " " << last_y << endl;
- }
- int main(){
- int n;
- cin >> n;
- spiral(n);
- return 0;
- }
Add Comment
Please, Sign In to add comment