This loop works as long as l is 1 and h can be any number. But i need it to work from different ranges such as l = 20 h = 40? Can anyone tell me how to do it? I would greatly appreciate it.
#include <iostream>
#include <vector>
#include <list>
#include <math.h>
#include <algorithm>
using namespace std;
int main(void)
{
int a, b, c, i = 0;
unsigned long l = 1;
unsigned long h = 25;
int array[3];
for ( a = l; l <= a && a <= h; ++a )
for ( b = a; l <= b && b <= h; ++b )
for ( c = b; l < c && c <= h; ++c )
if ( a * a + b * b == c * c )
{
array[0] = a;
array[1] = b;
array[2] = c;
if (array[0]+array[1]+array[2] <= h)
cout << array[0] << " " << array[1] << " " << array[2] <<endl;
else
break;
}
return 0;
}
If I understand you right, you're trying to bruteforce Diophant's system
a^2 + b^2 = c^2
a + b + c < h
this is the solution
#include <iostream>
using namespace std;
int main() {
const int l = 1;
const int h = 25;
for ( int a = l; a <= h; ++a )
for ( int b = l; b <= h; ++b )
for ( int c = l; c <= h; ++c )
if ((a * a + b * b == c * c ) &&
(a + b + c <= h))
cout << a << " " << b << " " << c <<endl;
return 0;
}
the output is:
3 4 5
4 3 5
6 8 10
8 6 10
if you don't need to distinguish a and b, second cycle could be
for ( int b = a; b <= h; ++b )
so you will get this:
3 4 5
6 8 10
There is something funny with this line, I can't tell what you are trying to do...
for ( a = l; l <= a && a <= h; ++a )
So, on the first round a=l, a++, and the condition is checked l<=a. a will be l+1, which means that l<=l+1, so you are going to exit your loop after the first time. I suspect that is not the behavior you want, but I really don't know what you do want. I could speculate that you want something like this:
for ( a = 0; l <= a && a <= h; ++a )
EDIT: From your comments, I can see what you are trying to do, and this should work better. Basically, you don't need to have the conditional for the lower value, it is the root of your problems. Also, I don't see why you bother to put the values into an array, which is written over each time, so I removed that.
for ( a = l; a <= h; ++a ) {
for ( b = a; b <= h; ++b ) {
for ( c = b; c <= h; ++c ) {
if ( a * a + b * b == c * c ) {
if (a+b+c <= h) {
cout << a << " " << b << " " << c <<endl;
}
else {
break;
}
}
}
}
}
I think one problem is in your third loop, which is slightly different from the other two:
for ( c = b; l < c && c <= h; ++c ) {
On the first pass, a == 1 and b == 1 and l == 1 so c is set to 1, and l < c evaluates to false, so the inner loop does not execute.
You really don't need to test your lower bounds (the l < c, or l <= b etc in earlier loops) because you know from the way you set them up that the condition should be true, except when you make a typo in the condition.
The canonical form for a for loop in C++ is:
for (int i = lo; i < hi; ++i)
for a suitable type (int here), index variable (i) going from a lower bound lo up to but not including an upper bound hi. This works in C99 too, but not C89. If you need the loop index's value after the loop completes, you might declare the variable at larger scope than just the loop as shown, but you usually avoid doing that. (I used i++ in a comment because I'm an unreformed C programmer, but the pre-increment is better in C++ in general.)
at the first loop the condition will be false from the first time because l>a
Related
I want it to not display the result of the sum if the numbers are lower or equal to 1 or 1000. I don't know if using if is the best way, but that's what I tried using, and I don't really understand why it doesn't work. I also tried writing conditions with || and &&, but those don't work either.
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int sum;
int a, b, c;
int main() {
cin >> a;
cin >> b;
cin >> c;
sum = a + b + c;
if ( 1 <= a, b, c <= 1000) { //also tried ( 1 <= a || b || c <= 100) and ( a, b, c >= 1 && a, b, c <= 1000)
cout<< sum;
}
else {
cout<< "can't calculate";
}
return 0;
}
The expression in this if statement
if ( 1 <= a, b, c <= 1000)
is an expression with the comma operator. It is equivalent to
if ( ( 1 <= a ), ( b ), ( c <= 1000 ) )
and the value of the expression is the value of its last operand. That is this if statement is equivalent to
if ( ( c <= 1000 ) )
It seems you mean
if ( 1 <= a && a <= 1000 && 1 <= b && b <= 1000 && 1 <= c && c <= 1000 )
{
std::cout << a + b + c << '\n';
}
Pay attention to that there is no sense to calculate the sum
sum = a + b + c;
before the checking the values of the variables a, b and c in the if statement.
Why do you have so much includes?
Your code just need iostream. Anything else could be removed.
Your if-condition doesn't have the right syntax. You can't write "a and b and c should be under 1000", you must do it for every var. Try:
a >= 1 && a <= 1000 &&
b >= 1 && b <= 1000 &&
c >= 1 && c <= 1000
You probably want this:
if ( a >= 1 && b >= 1 && c >= 1 &&
a <= 1000 && b <= 1000 && c <= 1000 )
{
std::cout << a + b + c;
}
Your code is not correct. You have to use the correct syntax.
Note: see Why is "using namespace std;" considered bad practice?
Link of Question : https://www.codechef.com/JULY20B/problems/PTMSSNG
Question Statement
Chef has N axis-parallel rectangles in a 2D Cartesian coordinate system. These rectangles may intersect, but it is guaranteed that all their 4N vertices are pairwise distinct.
Unfortunately, Chef lost one vertex, and up until now, none of his fixes have worked (although putting an image of a point on a milk carton might not have been the greatest idea after all…). Therefore, he gave you the task of finding it! You are given the remaining 4N−1 points and you should find the missing one.
Can anyone suggest where I'm going wrong or update my code or share a few test cases.
#include <iostream>
#include <vector>
#include <algorithm>
#include <utility>
#define ll long long
using namespace std;
int main()
{
int t;
cin >> t;
for (int i = 0; i < t; i++)
{
vector<pair<ll, ll>> v;
ll n, m, a;
bool checkx = false;
cin >> n;
m = 4 * n - 1;
ll x[m], y[m];
ll c, d;
a = (m - 1) / 2;
for (ll i = 0; i < m; i++)
{
cin >> x[i] >> y[i];
v.push_back(make_pair(x[i], y[i]));
}
sort(v.begin(), v.end());
for (ll i = a; i >= 1; --i)
{
if (v[2 * i].first != v[2 * i - 1].first)
{
c = v[2 * i].first;
checkx = true;
if ((2 * i) % 4 == 0 && i >= 2)
{
if (v[2 * i].second == v[2 * i + 1].second)
{
d = v[2 * i + 2].second;
}
else
{
d = v[2 * i + 1].second;
}
}
else
{
if (v[2 * i].second != v[2 * i - 1].second)
{
d = v[2 * i - 1].second;
}
else
{
d = v[2 * i - 2].second;
}
}
break;
}
}
if (checkx)
{
cout << c << " " << d;
}
else
{
if (v[0].second == v[1].second)
{
d = v[2].second;
}
else
{
d = v[1].second;
}
cout << v[0].first << " " << d;
}
cout << endl;
}
return 0;
}
You don't need to do such complex things. Just input your x and y vectors and xor every element of each vector. The final value will be the required answer.
LOGIC :
(a,b)------------------(c,b)
| |
| |
| |
| |
(a,d)------------------(c,d)
See by this figure, each variable (a, b, c, d) occurs even number of times. This "even thing" will also be true for the N rectangles. Hence, you have to find the values of x and y which are occurring odd number of times.
To find the odd one out in such cases, the best trick is to xor every element of the vector. This works because of these properties of xor : k xor k = 0 and k xor 0 = k.
CODE:
#include <functional>
#include <iostream>
#include <numeric>
#include <vector>
signed main() {
std::size_t t, n;
std::cin >> t;
while (t--) {
std::cin >> n;
n = 4 * n - 1;
std::vector<int> x(n), y(n);
for (std::size_t i = 0; i < n; ++i)
std::cin >> x.at(i) >> y.at(i);
std::cout << std::accumulate(x.begin(), x.end(), 0L, std::bit_xor<int>()) << ' '
<< std::accumulate(y.begin(), y.end(), 0L, std::bit_xor<int>()) << '\n';
}
return 0;
}
here is a test case that your code doesn't work:
1
2
1 1
1 4
4 6
6 1
9 6
9 3
4 3
the output of your code is (6,3),but it should be (6,4).
I guess you can check more cases where the rectangles intersects.
from functools import reduce
for _ in range(int(input())):
n=int(input())
li=[]
li1=[]
for i in range(4*n-1):
m,n=map(int,input().split())
li.append(m)
li1.append(n)
r =reduce(lambda x, y: x ^ y,li)
print(r,end=' ')
r =reduce(lambda x, y: x ^ y,li1)
print(r,end=' ')
print()
Problem is :
Write a function that as an input argument receives a three-digit positive number and as a result has to get the sum between the largest and the smallest number obtained by the same 3 digits divided by the median digit.
Example: input argument to function 438
The largest with the same digits is 843, the smallest is 348, so it should be calculated (843 + 348) / 4.
I have tried it and got the result ok but my code seems to complicated so iam asking is there a better way to do it?
Thanks in advance
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
int check(int x) {
int a, b, c, biggestNum, smallestNum, medianNum;
a = x / 100;
b = (x / 10) % 10;
c = x % 10;
if (a > b && a > c && b > c) {
biggestNum= a * 100 + b * 10 + c;
smallestNum= c * 100 + b * 10 + a;
medianNum= b;
}
else if (a > b && a > c && b < c) {
biggestNum= a * 100 + c * 10 + b;
smallestNum= b * 100 + c * 10 + a;
medianNum= c;
}
else if (b > a && b > c && a < c) {
biggestNum= b * 100 + c * 10 + a;
smallestNum= a * 100 + c * 10 + b;
medianNum= c;
}
else if (b > a && b > c && a > c) {
biggestNum= b * 100 + a * 10 + c;
smallestNum= c * 100 + a * 10 + b;
medianNum= a;
}
else if (c > a && c > b && a > b) {
biggestNum= c * 100 + a * 10 + b;
smallestNum= b * 100 + a * 10 + c;
medianNum= a;
}
else if (c > a && c > b && a < b) {
biggestNum= c * 100 + b * 10 + a;
smallestNum= a * 100 + b * 10 + c;
medianNum= b;
}
cout << "Smallest number is: " << smallestNum<< " ,biggest is: " << biggestNum << " and median is: " << medianNum<< "." << endl;
return (biggestNum + smallestNum) / medianNum;
}
int main() {
cout << "Enter one 3 digit positive number: ";
int x;
cin >> x;
float result = check(x);
cout << "The result is: " << result << "." << endl;
system("pause");
return 0;
}
The posted code can't really produce the right answer, considering that the result is calculated with integer arithmetic:
int check(int x) // <- note the type of the returned value
{
int biggestNum, smallestNum, medianNum;
// ...
return (biggestNum + smallestNum) / medianNum; // <- This is an integer division
}
int main()
{
int x;
// ...
float result = check(x); // Now it's too late to get the right result
}
The logic also doesn't consider all the possible cases, as a matter of fact it ignores duplicated digits and the big if else if construct, lacking a default branch (a final unconditioned else), leaves those uninitialized variables undetermined so that the following operation gives a meaningless result.
Given the assignment restrictions, I'd write something like the following
#include <utility>
// The assignment is about 3-digit numbers, you should check that x is actually in
// the range [100, 999]. Note that one of the extremes is a special case.
// Well, both, actually.
double I_ve_no_idea_how_to_name_this(int x)
{
constexpr int base = 10;
int smallest = x % base;
x /= base;
int median = x % base;
x /= base;
// Note that this "works" (extracting the third digit) even if
// x isn't a 3-digit number. If you can assure the input is well
// defined, you can simplify this.
int biggest = x % base;
// Now we can sort the previous variables.
using std::swap;
if ( median < smallest ) {
swap(median, smallest);
}
// Now I know that smallest <= median
if ( biggest < median ) {
swap(biggest, median);
}
// Now I know that median <= biggest
// ...
// Is that enough or am I missing something here?
// Please think about it before running the code and test it.
// Once the variables are sorted, the result is easily calculated
return (biggest + smallest + base * (2 * median + base * (biggest + smallest)))
/ static_cast<double>(median);
}
First, you should use more descriptive variable names and should initialize each variable on definition. These two steps help greatly in squashing bugs in complex programs. I know this one isn't complex, but it's a good habit to have. Second, the standard library can help with finding the largest and smallest digit, which then makes the rest simple. So here's an example without any if statements.
Finally, using namespace std; is a bad practice and should be avoided.
double check(int x)
{
int a = x / 100;
int b = (x / 10) % 10;
int c = x % 10;
int bigdigit = std::max({ a, b, c }); // find largest
int smalldigit = std::min({ a, b, c }); //find smallest
int middledigit = a + b + c - bigdigit - smalldigit; // sum of all digits minus largest and smallest gives the remaining one
int biggest = smalldigit + middledigit * 10 + bigdigit * 100;
int smallest = smalldigit * 100 + middledigit * 10 + bigdigit;
std::cout << "biggest: " << biggest << '\n';
std::cout << "smallest: " << smallest << '\n';
std::cout << "median: " << middledigit << '\n';
return (1.0 * biggest + 1.0 * smallest) / (1.0 * middledigit); --using double instead of int, as result could be fractional
}
try this...
int check(int x) {
int a,b,c,temp;
a = x/100;
b = (x/10)%10;
c = x%10;
if(b>a){
temp=a;
a=b;
b=temp;
}
if(c>b){
temp=b;
b=c;
c=temp;
}
if(b>a){
temp=a;
a=b;
b=temp;
}
cout << "smallest: " << a+(b*10)+(c*100) << "\n";
cout << "biggest: " << (a*100)+(b*10)+c << "\n";
cout << "median: " << b << "\n";
return (((a+c)*100)+(2*b*10)+(a+c))/b;
}
check this check function.
int check(int x) {
if(x >= 1000) x %= 1000; //or return -1;
//get digits
int M = x/100;
int C = (x/10)%10;
int m = x%10;
//unrolled bubble sort.
if(M < C) swap(M,C);
if(C < m) swap(C,m);
if(M < C) swap(M,C);
//simplified formula
return ((m+M)*(101))/C + 20;
}
//derivation of formula
B = M*100 + C*10 + m;
s = m*100 + C*10 + M;
B+s = (m+M)*100 + C*20 + (m+M)
= (m+M)*(100 + 1) + C*20
(B+s)/C = ((m+M)*(100 + 1) + C*20)/C
= ((m+M)*(101))/C + 20
The question need the user input two value, P and Q. The program then will output the number of right angle integer triangle as well as its perimeter from P to Q.
For example:
Input:
154 180
Output:
154 1
156 1
160 1
168 3
176 1
180 3
I think i need to find out the Pythagorean Triples in the P-Q range, but how to count the " number of right-angled triangle " ?
Here are my code :
#include <iostream>
#include <math.h>
using namespace std;
int main() {
int P, Q, a, b, c, i = 0;
cin >> P >> Q;
for ( a = P; a <= Q; ++a)
{
for ( b = a; b <= Q; ++b)
{
for ( c = b; b <= Q; ++c)
{
if ((pow(a, 2) + pow(b, 2)) == pow(c, 2) && a + b + c <= Q)
{
i +=1;
cout << a + b + c << " " << i << endl;
}
}
}
}
return 0;
}
Super Thanks !!
We can count the right angle integer triangles with a specific perimeter by std::map which has the perimeters as keys and the number of triangles as values:
std::map<int, int> triangle_map;
Next, using the symmetry of triangles of exchanging a and b with flipping, we can restrict our finding search into the case of a<=b.
But if a==b then c=sqrt(2)*a which is not an integer when a is an integer.
Therefore the following double-loop search would well work for us and can find all the target triangles:
const int Qmax_a = (Q-1)/2; // 1 is the minimum value of c.
for (int a = 1; a <= Qmax_a; ++a)
{
const int a_sqr = a*a;
for (int b = a+1; b <= Q-a-1; ++b)
{
const int two_side_sqr = a_sqr + b*b;
// possible candidate
const int c = static_cast<int>(std::round(std::sqrt(two_side_sqr)));
const int perimeter = (a+b+c);
if((c*c == two_side_sqr) && (P <= perimeter) && (perimeter <= Q)){
triangle_map[perimeter] += 1;
}
}
}
Finally, we can get the desired output from the resulted map:
DEMO
for(const auto& p : triangle_map){
std::cout << p.first << "," << p.second << std::endl;
}
I'm well aware this brute force method is bad and that I should be using something like Euclid's formula, and that the final loop isn't needed as c = 1000 - (a + b) etc... but right now I just want this to work.
bool isPythagorean(int a, int b, int c) {
if((a*a + b*b) == c*c && a < b && b < c) {
cout << a << " " << b << " " << c << endl;
return true;
} else {
return false;
}
}
int main()
{
int a = 1;
int b = 2;
int c = 3;
for(a = 1; a < b; ++a) {
for(b = 2; b < c; ++b) {
for(c = 3; a + b + c != 1000 && !isPythagorean(a, b, c); ++c) {
}
}
}
return 0;
}
For the most part, the code works as I expect it to. I cannot figure out why it is stopping shy of a + b + c = 1000.
My final triplet is 280 < 294 < 406, totalling 980.
If I remove the a < b < c check, the triplet becomes 332, 249, 415 totalling 996.
All results fit the pythagorean theorem -- I just cannot land a + b + c = 1000.
What is preventing me?
This part of the code iterates very strangely:
for(a = 1; a < b; ++a) {
for(b = 2; b < c; ++b) {
for(c = 3; a + b + c != 1000 && !isPythagorean(a, b, c); ++c) {
}
}
}
Initially, a = 1, b = 2, c = 3. But upon the first for(c), c=997, so the second iteration of for(b) will run up to b=996. Keep doing this, and at some point you find a triple (a,b,c), at that point, c is probably not close to 1000, b will iterate up to whatever state c was is in... and so on. I don't think you can accurately predict the way it's going to come up with triples.
I suggest you go with something like
for(a = 1; 3*a < 1000; ++a) {
for(b = a+1; a+2*b < 1000; ++b) {
for(c = b+1; a + b + c != 1000 && !isPythagorean(a, b, c); ++c) {
}
}
}
That way, loops won't depend on the previously found triple.
... and you really should use Euclid's method.
The condition in your innermost for loop explicitly says to never test anything where a + b + c is equal to 1000. Did you mean a + b + c <= 1000?
Alternate possible Solution:
#include <iostream>
#define S(x) x*x
int main() {
int c = 0;
for(int a=1;a<(1000/3);++a) {
// a < b; so b is at-least a+1
// If a < b < c and a + b + c = 1000 then 'a' can't be greater than 1000/3
// 'b' can't be greater than 1000/2.
for(int b=a+1;b<(1000/2);++b) {
c = (1000 - a - b); // problem condition
if(S(c) == (S(a) + S(b) ))
std::cout<<a*b*c;
}
}
return 0;
}
For additional reference please refer the following posts
Finding Pythagorean Triples: Euclid's Formula
Generating unique, ordered Pythagorean triplets