to print the output prescribed [closed] - c++

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
#include<iostream>
#include<math.h>
#include<stdlib.h>
using namespace std;
main()
{
int q,a,b,i,number;
cin>>q;
while(q--)
{
cin>>a>>b;
int a[b];
int number=1;
for(i=0;i<b;i++)
{
if(i==0)
{
a[i]=number;
number++;
}
a[i]=number;
if(number>0)
number=number*-1;
}
}
}
/*the above code i tried a little bit , but it's incomplete and may be incorrect too, you may help
i want to print the sequence as 1,2,-2,3,-3,3,4,-4,4,-4,5,-5,5,-5,5..... till n , where n is size of array in c++?*/
Chef's kid, Junior chef loves playing with different series. Chef, impressed by his son's curiosity, gifts him a special series S on his birthday
S=1,2,-2,3,-3,3,4,-4,4,-4,.............
Now chef, eager to check the intelligence of his son, gives him q queries to solve. Each query consists of two positions a and b, and Junior_chef is required to calculate the sum of all integers from a to b.
Input
The first line of the input contains a single integer q, which denotes the number of queries. Next q lines consist of two integers, a and b.
Output
Print the answer in single line.
Constraints
1<=q<=10 , 1<=a,b<=10^12
Sample Input
1
1 4
Sample Output
4
Explanation : As the series is 1,2,-2,3, therefore the sum will be 4.

Do you mean the following?
#include <iostream>
int main()
{
while ( true )
{
std::cout << "Enter a non-negative number (0-exit): ";
int n = 0;
std::cin >> n;
if ( n <= 0 ) break;
for ( int i = 1; i <= n; i++ )
{
for ( int j = 0; j < i; j++ ) std::cout << ( j % 2 ? -i : i ) << ' ';
}
std::endl( std::cout );
}
return 0;
}
If to enter sequentially 1 2 3 4 5 6 7 0 then the output will be
Enter a non-negative number (0-exit): 1
1
Enter a non-negative number (0-exit): 2
1 2 -2
Enter a non-negative number (0-exit): 3
1 2 -2 3 -3 3
Enter a non-negative number (0-exit): 4
1 2 -2 3 -3 3 4 -4 4 -4
Enter a non-negative number (0-exit): 5
1 2 -2 3 -3 3 4 -4 4 -4 5 -5 5 -5 5
Enter a non-negative number (0-exit): 6
1 2 -2 3 -3 3 4 -4 4 -4 5 -5 5 -5 5 6 -6 6 -6 6 -6
Enter a non-negative number (0-exit): 7
1 2 -2 3 -3 3 4 -4 4 -4 5 -5 5 -5 5 6 -6 6 -6 6 -6 7 -7 7 -7 7 -7 7
Enter a non-negative number (0-exit): 0

Related

Is there a data type and enter number more than 10 billion in it and then make an operation on it like *

My program is to sum an arithmetic sequence from 1 to n like
-1 2 -3 4 -5 6 -7 etc...
But
n (1 ≤ n ≤ 10^15).
And when I execute this program, I am faced with that the sum variable is overflowing although I use data type long long
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
long long n;
cin >>n;
if (n%2!=0)
{
long long sump = ((n-1)/4.0) * (2+(n-1));
long long sumn = ((n+1)/4.0) * (-1-n);
long long sum = sump + sumn;
cout << sum << endl;
}
else
{
long long sump = ((n)/4.0) * (2+(n));
long long sumn = ((n)/4.0) * (-1-(n-1));
long long sum = sump + sumn;
cout << sum << endl;
}
}
If you see such big numbers in questions, then most often you cannot solve that by brute force, running big loops and the like.
You need to find an analytical or mathematical solution.
Even, if you do not know the solution, you may look at example values.
If you look at your series, then you can see something like the below:
Index Sign Series Sum
0 1 0 0
1 -1 -1 -1
2 1 2 1
3 -1 -3 -2
4 1 4 2
5 -1 -5 -3
6 1 6 3
7 -1 -7 -4
8 1 8 4
9 -1 -9 -5
10 1 10 5
As you can see,
if n is even, then the result is n/2
if n is odd then the result is -((n/2)+1)
And this can be easily implemented . . .

How can I find the prime numbers?

How can I find the prime numbers in a one-dimensional array in C++ in a simple way ??
{
int list[5];
int i,sum = 0;
for (i = 0; i < 5; i++)
{
cout << "Enter The List [" << i << "]: "; cin >> list[i];
sum = sum + list[i];
}
cout << endl;
cout << "The Sum Is:" << sum << endl;
}
Emphasizing on the comment of #john:
Create a function (say bool is_prime(int n)).
Now check if the number n is a prime or not.
So, you need to check if each of the positive integers more than 1 before n divides n or not without leaving any remainder. There's a shorter workaround, which will greatly reduce the computational cost. Just checking till the square root of the number n will do. Hence the function sqrt() is used.
So now, our is_prime() function is pretty easy to build as you can see:
bool is_prime(int n)
{
int i,p=0;
for(i=2;i<=sqrt(n);i++)
{
if(n%i==0)
{
p=1;
break; //even if one integer divides the number, then it is composite.
}
}
if(p==1)
return false; //The number is a composite.
else
return true; //The number is a prime.
}
Now, you just need to pass every value of the array into this function, and your job will be done.
Also, this program can be made even better if you check for the special case of 1 which is neither composite nor prime. A suggestion is, check your array element if it is 1 or not. If not, then pass the value in the function, else just print that it is a 1.
NOTE: The sqrt() function is available in the cmath library in C++ so you need to include that in your program too.
You can use sieve of Eratosthenes. Simply how it works is it iterates (from 2) through an boolean array and if arr[i] is prime (is true, i is the given number), sets every multiplicity to false.
Start with an array filled with true
Numbers 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
is prime 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
first you have to set arr[0] and arr[1] to false, because these are not prime numbers
Numbers 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
is prime 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
Now, you go to 2 and set every multiplication of it to false.
in this case 4, 6, 8, 10, 12, 14 16...
Numbers 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
is prime 0 0 1 1 0 1 0 1 0 1 0 1 0 1 0 1 0
Then do it for 3
so 6, 9, 12, 15
Numbers 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
is prime 0 0 1 1 0 1 0 1 0 0 0 1 0 1 0 0 0
4 is not prime so you skip it
5 is prime so you do the same as for 2 and 3 (10 -> false, 15 -> false etc.)
after you use it, you can simply check if n is prime
if (arr[n] == true)
cout << n << " is prime";
else
cout << n << " is not prime";
you can find it easily on internet, for example here (there are some optimizations you can add, too)

Read integers from a text file into a two-dimensional array and assess the length

I need to read integers from a text file into a two-dimensional array.
-1 indicates the end of array. Every array supposes to have 6 positive integers (-1 does NOT count as part of the array).
For example, if my text file contains the following integers:
1 3 4 6 1 7 -1 1 3 5 7 2 3 -1 2 5 7 2 6 3 -1
That means when these integers are read into the program, there will be 3 arrays:
1st Array: 1 3 4 6 1 7
2nd Array: 1 3 5 7 2 3
3rd Array: 2 5 7 2 6 3
I wrote a program to assess if each array has a correct length (6 integers) AND correct integers (all integers should be positive) and output corresponding error messages if these criteria are not met.
#include <iostream>
#include <fstream>
#include <string>
#define MAX_ROWS 3
#define MAX_COLUMNS 2
using namespace std;
int main()
{
string fileName = "testdata.txt"; //declare a string to store the Input File's name
ifstream inFile; //name the input file connection
inFile.open(fileName); //open the Input File
string errorMessage = "Input file cannot be found"; //Declare a string to store an error message, just in case the Input file doesn't exist or cannot be found
if (!inFile) { //If the Input File doesn't not exist, then display the error message
cout << errorMessage << '\n'; //also store the error message to the Output file
system("pause");
return 0; //end the program if the Input File does not exist
}
int checkNbr;
int ArrB[MAX_ROWS][MAX_COLUMNS];
int size = MAX_ROWS * MAX_COLUMNS;
bool bad = false;
bool invalidnum = false;
while (!inFile.eof())
{
for (int i = 0; i < MAX_ROWS;i++) {
for (int j = 0; j < MAX_COLUMNS; j++) {
inFile >> ArrB[i][j];
if (ArrB[i][j] == -1) {
bad = true;
cout << "\nThe array does not have enough integers" << endl;
break;
//return 1;
}
else {
if (ArrB[i][j] < 1) {
invalidnum = true;
}
}
cout << *(*(ArrB + i) + j) << " ";
}
}
if (invalidnum == true) {
invalidnum = false;
cout << "\nThere is/are negative number(s) or zero(s) in the array imported from your text file.\n";
}
if (bad == false) {
inFile >> checkNbr;
if (checkNbr == -1) {
cout << "\nThe size of the array is correct." << endl;
}
else {
while (checkNbr != -1)
{
cout << checkNbr;
cout << " ";
inFile >> checkNbr;
}
cout << "\nYou have too many numbers in this array\n";
}
}
}
return 0;
}
If I run my program:
Case 1 - PASSED
1 2 3 4 5 6 -1 3 5 2 1 6 8 3 2 5 -1 3 3 5 6 7 5 -1
Case 2 – PASSED
1 2 3 4 5 -6 -1 3 -5 2 1 6 8 -1 3 5 6 7 5 -1
Case 3 – FAILED(!)
1 2 3 4 -1 1 2 3 4 5 6 7 8 -1 1 2 3 4 5 -1
As you can see, case 3 failed. The second array (1 2 3 4 5 6 7 8) is actually longer than the declared array size, but it’s printing out “The array does not have enough integers” error message…..
The ONLY time this program won't work is when the first array does not have enough integers.
Any comments or hints would be appreciated!
The problem
bad is not reset after processing it.
Solution
Move bool bad = false; into the while (!inFile.eof()) loop body so it gets reset every iteration. If you define variables with the narrowest possible scope you can usually avoid this problem, so you should strongly consider doing the same thing with the rest of your variables.
This will solve the bug that was asked about and at least one other bug you haven't found yet. This leaves at least two more outstanding bugs for you to resolve, and both have been covered in the question's comments.
TL;DR version
A quick walk through of input 1 2 3 4 -1 1 2 3 4 5 6 7 8 -1 1 2 3 4 5 -1
1 2 3 4 -1 is parsed and found to be bad, so bad is set to true and the testing for a too-long value and clean-up is skipped. The file hasn't ended, so the program loops and starts reading the next array.
input remaining:
1 2 3 4 5 6 7 8 -1 1 2 3 4 5 -1
output so far:
1 2 3 4
The array does not have enough integers
1 2 3 4 5 6 is parsed. This fills the array and the for loops exit. bad is still true, so the check for overflow is skipped and no message is printed.
Input remaining:
7 8 -1 1 2 3 4 5 -1
output so far:
1 2 3 4
The array does not have enough integers
1 2 3 4 5 6
Now 7 8 -1 is parsed. This is too short to be an array and reported. Take careful note of what this does to the output.
Input remaining:
1 2 3 4 5 -1
output so far:
1 2 3 4
The array does not have enough integers
1 2 3 4 5 6 7 8
The array does not have enough integers
Whoops. Looks like 1 2 3 4 5 6 7 8, not merely 7 8, was too short.
the program then parses 1 2 3 4 5 and finds it to be too short.
Input remaining:
output so far:
1 2 3 4
The array does not have enough integers
1 2 3 4 5 6 7 8
The array does not have enough integers
1 2 3 4 5
The array does not have enough integers

Codechef is rejecting my solution

I am newbie on codechef and i was trying to solve the following question however my code runs fine on my machine, i also tested it with some cases.
Question is as follows :-
In Byteland it is always the military officer's main worry to order his soldiers on parade correctly. Luckily, ordering soldiers is not really such a problem. If a platoon consists of n men, all of them have different rank (from 1 - lowest to n - highest) and on parade they should be lined up from left to right in increasing order of rank.
Sounds simple, doesn't it? Well, Sgt Johnny thought the same, until one day he was faced with a new command. He soon discovered that his elite commandos preferred to do the fighting, and leave the thinking to their superiors. So, when at the first rollcall the soldiers lined up in fairly random order it was not because of their lack of discipline, but simply because they couldn't work out how to form a line in correct order of ranks. Sgt Johnny was not at all amused, particularly as he soon found that none of the soldiers even remembered his own rank. Over the years of service every soldier had only learned which of the other soldiers were his superiors. But Sgt Johnny was not a man to give up easily when faced with a true military challenge. After a moment's thought a solution of brilliant simplicity struck him and he issued the following order: "men, starting from the left, one by one, do: (step forward; go left until there is no superior to the left of you; get back in line).". This did indeed get the men sorted in a few minutes. The problem was solved... for the time being.
The next day, the soldiers came in exactly the same order as the day before, and had to be rearranged using the same method. History repeated. After some weeks, Sgt Johnny managed to force each of his soldiers to remember how many men he passed when going left, and thus make the sorting process even faster.
If you know how many positions each man has to walk to the left, can you try to find out what order of ranks the soldiers initially line up in?
Input
The first line of input contains an integer t<=50, the number of test cases. It is followed by t test cases, each consisting of 2 lines. The first line contains a single integer n (1<=n<=200000). The second line contains n space separated integers wi, denoting how far the i-th soldier in line must walk to the left when applying Sgt Johnny's algorithm.
Output
For each test case, output a single line consisting of n space separated integers - the ranks of the soldiers, given from left to right in their initial arrangement.
Example
Input:
2
3
0 1 0
5
0 1 2 0 1
Output:
2 1 3
3 2 1 5 4
Warning: large Input/Output data, be careful with certain languages
#include <iostream>
#include <string.h>
using namespace std;
int main ()
{
int t,n;
cin >> t;
while(t>0){
cin >> n;
int array[n+1];
int stepsmoved,i;
for(i = 1; i <= n; i++){
array[i] = i;
}
for(i = 1; i <=n; i++){
cin >> stepsmoved;
if(stepsmoved == 0){}
else{
int x;
x = array[i];
for (int j = i; j> i- stepsmoved; j--){
array[j] = array[j-1];
}
array[i-stepsmoved] = x;
}
}
for(i = 1; i <= n; i++){
cout<<array[i]<<" ";
}
cout<<endl;
t--;
}
return 0;
}
So is there something logically or syntactically wrong?
The order of 'unwinding' the sorting is relevant.
Here is the code that demonstrates the statement above (the ranks are 1-based, the 1 - is highest, 10 - is lowest, array indices are 0-based):
#include <stdio.h>
void dump(int *a) {
int i;
for (i = 0; i < 10; i++)
printf("%d ", a[i]);
printf("\n");
}
int main() {
int array[10] = {0}, steps[10] = {0};
int i,j;
srand(0);
// Assign ranks in random order
for (i = 0; i < 10;) {
j = rand() % 10;
if (!array[j])
array[j] = ++i;
}
dump(array);
// Sort according to the Sgt Johnny's initial idea
for (i = 1; i < 10; i++) {
for (j = 0; array[j] < array[i]; j++);
if (j < i) {
int k, temp = array[i];
for (k = i; k > j; k--) {
array[k] = array[k-1];
steps[temp-1]++;
}
array[j] = temp;
dump(array);
}
}
printf("Steps:\n");
dump(steps);
printf("\n");
// reconstruct the origina order
#if 1
for (i = 10-1; i >= 0; i--)
#else
for (i = 0; i < 10; i++)
#endif
{
int s = steps[array[i]-1];
for (j = i; s; s--, j++) {
int temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
dump(array);
}
}
If the reconstruction is done in reverse order, then we get a sequence that matches original:
8 7 5 1 10 4 2 3 9 6
7 8 5 1 10 4 2 3 9 6
5 7 8 1 10 4 2 3 9 6
1 5 7 8 10 4 2 3 9 6
1 4 5 7 8 10 2 3 9 6
1 2 4 5 7 8 10 3 9 6
1 2 3 4 5 7 8 10 9 6
1 2 3 4 5 7 8 9 10 6
1 2 3 4 5 6 7 8 9 10
Steps:
3 5 5 4 2 4 1 0 1 0
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 10 9
1 2 3 4 5 6 7 8 10 9
1 2 3 4 5 6 8 7 10 9
1 2 3 4 5 8 7 10 9 6
1 2 3 4 8 7 5 10 9 6
1 2 3 8 7 5 10 4 9 6
1 2 8 7 5 10 4 3 9 6
1 8 7 5 10 4 2 3 9 6
8 7 5 1 10 4 2 3 9 6
Otherwise, the reconstructed order does not match the original:
8 7 5 1 10 4 2 3 9 6
7 8 5 1 10 4 2 3 9 6
5 7 8 1 10 4 2 3 9 6
1 5 7 8 10 4 2 3 9 6
1 4 5 7 8 10 2 3 9 6
1 2 4 5 7 8 10 3 9 6
1 2 3 4 5 7 8 10 9 6
1 2 3 4 5 7 8 9 10 6
1 2 3 4 5 6 7 8 9 10
Steps:
3 5 5 4 2 4 1 0 1 0
2 3 4 1 5 6 7 8 9 10
2 4 1 5 6 7 3 8 9 10
2 4 5 6 7 1 3 8 9 10
2 4 5 7 1 3 8 6 9 10
2 4 5 7 3 8 6 1 9 10
2 4 5 7 3 8 6 1 9 10
2 4 5 7 3 8 1 9 10 0
2 4 5 7 3 8 1 10 9 0
2 4 5 7 3 8 1 10 0 9
2 4 5 7 3 8 1 10 0 6

Need help reading from a file until end of line

I'm working on a a project for my class where I have to use all four algorithms for the maximum subarray sub problem (cubic, quadratic, linear, and recursive). My problem is that I'm supposed to read the input from a file and I'm having trouble figuring out how to read until the end of a line, execute code with that data, and then move onto the next line. The input file looks like this:
2
-5 -10 -2 -4
2
-2 10 -5 -6
3
-10 -5 0 5 -20 20 -50
4
10 8 2 -20 -50 -100 -150
0
-1 -2 -3 -4 -5
1
-100 -200 0
4
200 500 -700 1000 2000 -5000 4 10
4
100 200
6
0 0 0 0 0 0 -10
5
-4 10 -3 200 500 -700 2
0
5 10 15 20 25 30 35
2
10 30 50 70 100
3
-15 16 23 -30 0 -2 13 8 6 0 -4 -15
12
9 8 23 -1 -23 -4 0 0 4 7 9 10 -23 68 1 -2 -3 -6 -19 10 5 1 1 2 4 3 -46 12 -100 78 -23 0 0 12 2 7
5
-1 -3 0 2 3 6 1 -5 -3 -2
now my issue is that I want to be able to read in a single number (the minimum subarray length) and then fill the array with the row of numbers below it, then execute all four algorithms using that data, then I want to move on to the next minimum subarray length and the next array of values below it, execute all four algorithms etc., and I want to be able to do this all in one go.
For example, I want to read 2 as the minimum subarray length, then use (-5,-10,-2,-4) as the array, execute all four algorithms, then use 2 as the minimum length, (-5,10,-5,-6) as the array, execute all four algorithms, and keep doing that until the end of the file.
Here is a quick possible solution that might help ("test.txt" contains your values...)
#include <fstream>
#include <iostream>
#include <sstream>
#include <vector>
using namespace std;
int main()
{
ifstream in("test.txt");
string str;
int value;
while (in)
{
vector<int> vec;
getline(in, str);
stringstream stream(str);
while (stream)
{
stream >> value;
vec.push_back(value);
}
vec.erase(vec.end()-1);
//Here the vec conntains all values of the current line
for (auto v : vec)
cout << v << " ";
cout << endl;
}
}