I have a small problem. I'm working on a project that have to print all the partitions of an integer, in this way. For example:
5 = 5
5 = 4 + 1
5 = 3 + 2
5 = 3 + 1 + 1
5 = 2 + 2 + 1
5 = 2 + 1 + 1 + 1
5 = 1 + 1 + 1 + 1 + 1
.
So there is my solution:
#include <iostream>
using namespace std;
void printArray(int p[], int n) {
for (int i = 0; i < n; i++)
cout << p[i]<<" + " ;
cout<<endl;
}
void printAllUniqueParts(int n) {
int p[n];
int k = 0;
p[k] = n;
while (true)
{
cout<<n<<" = ";
printArray(p, k + 1);
int rem_val = 0;
while (k >= 0 && p[k] == 1)
{
rem_val += p[k];
k--;
}
if (k < 0)
return;
p[k]--;
rem_val++;
while (rem_val > p[k])
{
p[k + 1] = p[k];
rem_val = rem_val - p[k];
k++;
}
p[k + 1] = rem_val;
k++;
}
}
It prints them in a correct order, but the problem is that it prints an extra + at the end. I can't find the problem. It may be very small bug, but I cant see it. Could you please check this out, and share your ideas?
Only print the "+" if you are not at the end of the range.
cout << p[i]; if (i+1 < n) cout << " + " ;
The problem is very obvious:
for (int i = 0; i < n; i++)
cout << p[i]<<" + " ;
The code you wrote prints a + after every number. So that's exactly what it's going to do. Just because you don't want a + to appear after the last number, that's not going to happen unless the program is coded to do so.
There are several common, simplest techniques for formatting this kind of output. The simplest one is not to print the + after the number, but before it, and simply not print it before the first number. It's often logically simpler to take a non-default option for the first step, instead of the last one, since you do not have to figure out which one is the last one:
for (int i = 0; i < n; i++)
{
if (i > 0)
cout << " + ";
cout << p[i];
}
Related
So I was trying to make a matrix where the elements of the main diagonal would increase by 3 one by one and I also wanted to change the values of the previous and the next element of the the main diagonal with their predecessor and succesor.
Something like this:
It all worked fine until the predecessor element. For some reason v[i][j-1] doesn't work?
I would like to mention I am a beginner.
Here is the code:
#include <iostream>
using namespace std;
int n, v[22][22];
int main()
{
cin >> n;
int k = 1;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (i == j)
{
v[i][j] = k;
v[i][j + 1] = k + 1;
v[i][j - 1] = k - 1; //this is the part where it doesn't work
}
cout << v[i][j] << " ";
}
k += 3;
cout << "\n";
}
}
Here is the result I am getting
Edit: I also tried it when i and j start from 1, so there won't be any negative index value. It still doesn't work.
For starters there is no need to use nested for loops. It is enough to use only one for loop.
When i is equal to 0 and j is equal to 0 then this expression v[i][j - 1] access memory outside the array that invokes undefined behavior.
The same problem exists when n is equal to 22 for the expression and i and j are equal to n - 1 for this v[i][j + 1] .
You should check these situations.
And this output
cout << v[i][j] << " ";
can occur for v[i][j-1] when it was not yet updated.
Also try to declare variables in minimum scope where they are used. For example there is no need to declare the array in the global namespace.
Here is shown how you can organize the loops.
int value = 1;
for (size_t i = 0; i < n; i++)
{
v[i][i] = value;
if (i != 0) v[i][i - 1] = value - 1;
if (i != n - 1) v[i][i + 1] = value + 1;
value += 3;
}
for (const auto &row : v)
{
for (const auto &item : row)
{
std::cout << std::setw( 3 ) << item << ' ';
}
std::cout << '\n';
}
For example if n is equal to 5 then the output will be
1 2 0 0 0
3 4 5 0 0
0 6 7 8 0
0 0 9 10 11
0 0 0 12 13
I am having issues with a task I've done, it outputs answer correctly without any errors. It gives me 2/3 points, last shows error, and doesn't show what. I've no clue what I've done wrong. Can someone have a look at this please.
Task:
A perfect number is a natural number that is equal to the sum of all its natural divisors (different from itself).
6 = 1 + 2 + 3
28 = 1 + 2 + 4 + 7 + 14
A redundant number is a natural number which is greater than the sum of all its natural divisors (different from itself).
9> 1 + 3
The deficit number is a natural number that is less than the sum of all its natural divisors (different from itself).
12 <1 + 2 + 3 + 4 + 6
Input
A natural number N (N <1000) followed by N natural numbers (not greater than 32000).
Remember 0 is an natural number.
For each of the numbers given in the input, the program should print a line of the form on the screen:
X - perfect / redundant / deficit number
depending on the type of number.
Sample input
6 15 28 6 56 22 496
Sample output
15 - redundant number
28 - perfect number
6 - perfect number
56 - deficit number
22 - redundant number
496 - a perfect number
#include <iostream>
using namespace std;
void ifPerfect(int n)
{
int sum = 0;
for (int i = 1; i <= n / 2; i++)
if (n % i == 0)
sum += i;
if (sum == n)
{
cout << n << " - perfect number" << endl;
}
}
void ifRedundant(int n)
{
int sum = 0;
for (int i = 1; i < n; i++)
{
if (n % i == 0)
{
sum += i;
}
}
if (n > sum)
{
cout << n << " - redundant number" << endl;
}
}
void ifDeficit(int n)
{
int sum = 0;
for (int i = 1; i < n; i++)
{
if (n % i == 0)
{
sum += i;
}
}
if (n < sum)
{
cout << n << " - deficit number" << endl;
}
}
int main()
{
int n;
cin >> n;
if (n >= 0 && n < 1000)
{
int *tab = new int[n];
for (int i = 0; i < n; i++)
{
cin >> tab[i];
}
for (int i = 0; i < n; i++)
{
ifRedundant(tab[i]);
ifPerfect(tab[i]);
ifDeficit(tab[i]);
}
delete[] tab;
return 0;
}
}
According to Wiki (https://en.wikipedia.org/wiki/Perfect_number), 0 is NOT a perfect number, while your program would say that it is.
Given an input of 0, you program will produce an incorrect answer.
The clue was the statement "Remember 0 is an natural number."
While natural, it is not perfect.
So, I am trying to write a program to compute the value of the series 1/0! + 1/1! + 1/2! + .. + 1/n!. I think this is a pretty easy question to solve. But, the 1/0! i.e. the 1st term of the series is where it is creating all the problems for me. Please help me out. Please pardon for the silly mistakes if I have made since I started learning C++ 2 months ago and I am trying to solve various problems ever since.
#include <iostream>
using namespace std;
int fact(int j)
{
int facto = 1;
if (j == 0) {
return facto;
}
else {
for (int i = 2; i <= j; i++) {
facto = facto * i;
}
return facto;
}
}
int main()
{
int n, p;
float sum = 0, k;
cout << "Enter the value of n: " << endl;
cin >> n;
for (int i = 0; i < n; i++) {
p = fact(i);
cout << p << endl;
k = 1 / p;
cout << k << endl;
sum = sum + k;
}
cout << "Sum is: " << sum << endl;
return 0;
}
I have 2 questions :
1) When I am giving 0 as input, I am getting 0(i.e. the value of sum) as output(but, I am expecting to get 1) and, when I am giving 1 as input, it is giving 1 as output(expecting 2 as output). Please help me in pointing out the loophole.
2) When I am giving 0 as input, it is not printing the values of 'p' and 'k' but any input greater than 0 is showing the values of 'p' and 'k' for each time it completes the loop. Why ??
Change the loop the following way
for(int i=0; i<=n; i++)
^^^^^
Or change the loop to do-while loop as for example
int i = 0;
do
{
//...
} while ( i++ < n );
Also this statement
k = 1/p ;
change like
k = 1.0f/p ;
I am solving a problem in which I have to find those element from the array whose total gives maximum sum. But there is a condition that no two adjacent element can be the part of that max subarray. Here is my code using simple brute Force solution-
#include <bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin >> t;
while (t != 0)
{
int n, i, s, k = 0, m = -1001;
vector< int > a;
cin >> n;
a.resize(n, 0);
vector< int > b;
for (i = 0; i < n; i++)
{
cin >> a[i];
m = max(m, a[i]);
if (a[i] < 0)
{
a[i] = 0;
++k;
}
}
if (k == n)
cout << m;
else
{
k = 0;
s = a[0];
b.push_back(a[0]);
for (i = 1; i < n; i++)
{
if (i != k + 1)
{
if (a[i])
{
s += a[i];
b.push_back(a[i]);
k = i;
}
}
else
{
if (s - a[i - 1] + a[i] > s)
{
b.pop_back();
s -= a[i - 1];
s += a[i];
b.push_back(a[i]);
++k;
}
}
}
}
cout << endl;
for (i = n; i >= 0; i--)
{
if (b[i])
cout << b[i] << " ";
}
cout << endl;
--t;
}
return 0;
}
Here is input to code-
First line represent no. of test cases,
Second line represent size of array
And the next line shows array elements.m
5
5
-1 7 8 -5 4
4
3 2 1 -1
4
11 12 -2 -1
4
4 5 4 3
4
5 10 4 -1
Output-
4 8
32 32607 -787829912 1 3
32 32607 -787829912 12
3 5
10
Expected output-
4 8
1 3
12
3 5
10
So, there are 5 test cases. For the first test case and last two test case output is correct. But for second and third test case it is giving garbage value. What is the problem, that for some test cases it is giving garbage value, and for other not.
for (i = n; i >= 0; i--)
{
if (b[i])
cout << b[i] << " ";
}
This prints out n+1 values in b. But even in the best case, b only has n values (for n=1). And for n>1, b.size() is less than n, so you are reading garbage from outside the vector's storage (this is undefined behavior). Just use the correct bound:
for (i = b.size() - 1; i >= 0; ++i)
I think I found your (first) problem:
if(k==n)
cout<<m;
When all numbers are negative this outputs the largest of them.
But the empty array has a sum of 0 and is larger than a negative number and has no 2 adjacent members in it. So clearly the right answer should be 0, not m.
How can I output the below asterisks in rhombus shape in c++ using the least number of loops and variables. Maximum no. of stars = n (input taken from the user)
*
* *
* * * = n
* *
*
I tried doing it with just 2 loops but didn't succeed plus the program is too complicated to understand so didn't include it here.
So any algorithms you can think of?
That's not a pyramid, that's a rhombus :)
Anyway let's see the star number:
n=1 -> 1 star
n=2 -> 4 stars
n=3 -> 9 stars
The pattern looks like twice the sum from 1 to n minus n (because the middle row exists once not twice), so s(n) = 2 * (1+n)/2 * n - n = (1+n)*n-n = n*n hey it's the area of a square! Well how surprising. :-)
Now how to draw a n-sized rhombus:
there will be 2*n-1 rows
each row is w = 2*n-1 characters wide
each ith row (starting from i=0) has m = min(i+1, 2*n-1-i) stars, and m-1 spaces between them
so each row needs w - (m) - (m-1) spaces of space padding at sides, i.e. w/2 on left and on right.
Now go write it! :)
This is a common question for education I believe, and thus a Google search is very helpful.
Here is a ready made solution in Visual C++ (as some people learn better from code examples, the choice is yours)...
http://www.softwareandfinance.com/Visual_CPP/Loops_Diamond_Pattern.html
EDIT: Trying to reduce the for loops and keeping the spacing between stars, this is my best effort...
int i, j;
int n = 0;
std::cout << "Enter the maximum number of *:";
std::cin >> n;
std::cout << "\n\n";
for (i = 1; i <= n; i++)
{
std::cout.width(n - i);
std::cout.fill(' ');
std::cout << "";
for (j = 1; j <= i; j++)
std::cout << "* ";
std::cout.width(n - i);
std::cout.fill(' ');
std::cout << "";
std::cout << "\n";
}
for (i = n - 1; i >= 1; i--)
{
std::cout.width(n - i);
std::cout.fill(' ');
std::cout << "";
for (j = 1; j <= i; j++)
std::cout << "* ";
std::cout.width(n - i);
std::cout.fill(' ');
std::cout << "";
std::cout << "\n";
}
std::cout << "\n";
ONLY 2 LOOPS USED:
int i, j;
int n = 0, c = 0, inc = 1;
std::cout << "Enter the maximum number of *:";
std::cin >> n;
std::cout <<"\n\n";
for (i = 1; i <= (n * 2) - 1; i++)
{
c += inc;
if(i == n)
inc = -1;
std::cout.width(n - c);
std::cout.fill(' ');
std::cout << "";
for (j = 1; j <= c; j++)
std::cout << "* ";
std::cout.width(n - c);
std::cout.fill(' ');
std::cout << "";
std::cout <<"\n";
}
std::cout <<"\n";
Two loops? Surely you can get by with just one.. Here is a rough description of the alogirthm I came up with:
Loop through the (2*n-1)^2 square
Determine the amount of stars needed on the current row (i.e. distance to the row with n stars)
Determine the distance from the middle of the current index
If the absolute distance of the current index is smaller than the amount of stars on that row, it needs a star in odd/even indices depending if n is odd/even.
Add endlines end of rows
And here's a near IOCC-worthy quick improvisation of the algorithm that draws the rhombus with 2 variables, the loop counter and n=amount of stars in the middle row.
#include <cmath>
void print_rhombus(int n)
{
for (int i = 1; i <= ((2*n-1)*(2*n-1)); ++i) {
if ((abs((((2*n-1)+1)/2)-(i%(2*n-1) == 0?2*n-1:i%(2*n-1)))) - (n-abs((i%(2*n-1)==0?(i/(2*n-1)):(i/(2*n-1))+1) - n)) < 0 && (
(n%2==1 && ((n-abs((i%(2*n-1)==0?(i/(2*n-1)):(i/(2*n-1))+1) - n))%2==1 && (i%(2*n-1) == 0?2*n-1:i%(2*n-1))%2 == 1 || (n-abs((i%(2*n-1)==0?(i/(2*n-1)):(i/(2*n-1))+1) - n))%2==0 && (i%(2*n-1) == 0?2*n-1:i%(2*n-1))%2==0)) ||
(n%2==0 && ((n-abs((i%(2*n-1)==0?(i/(2*n-1)):(i/(2*n-1))+1) - n))%2==1 && (i%(2*n-1) == 0?2*n-1:i%(2*n-1))%2 == 0 || (n-abs((i%(2*n-1)==0?(i/(2*n-1)):(i/(2*n-1))+1) - n))%2==0 && (i%(2*n-1) == 0?2*n-1:i%(2*n-1))%2==1))
)) {
std::cout << "*";
} else {
std::cout << " ";
}
if (i%(2*n-1) == 0 && (n-abs((i%(2*n-1)==0?(i/(2*n-1)):(i/(2*n-1))+1) - n)) == n) {
std::cout << " = " << n << std::endl;
}
else if (i%(2*n-1) == 0) {
std::cout << std::endl;
}
}
}
It also prints the " = N", which I suppose may not have been the requirement. As you can see, sometimes a couple of extra descriptive variables would go a long ways. And if this were homework, you'd better be prepared to explain it..
Break the task down.
1) First write a program that outputs a square of asterisks. In the example above (n = 3, I think) a five by five square will contain all the asterisks you want to output. Two loops (one inside the other) is the way to do this.
2) Now you have all the asterisks you need, work out formulas for which asterisks should be skipped to get the diamond pattern you want. If you decide an asterisk should be skipped you output a space instead.
All programming is like this, you're faced with a complex problem, you break it down into smaller sub-problems.
Not filled rhombus like this one:
*
* *
* *
* *
* *
* *
*
Code c++:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int w=7;
int h=7;
string fill("*");
string empty(" ");
for (int i = 0; i<w; i++)
{
for (int j = 0; j<h; j++)
{
if((j == h/2-i) or (j == h/2+i) or (j == -h/2+i) or (j+i == h+h/2-1) ) cout << fill;
else cout <<empty;
}
cout<<endl;
}
}