Untitled UI logotext
Solutions
WebsitesEcommerceMobile AppsWeb AppsProduction Support & Maintenance
Our work
Company
About usBlogPodcastContact us
Book a free consultation

Project Euler Problem 9

Olivia Rhye

I've been having some fun doing the first few problems of Project Euler and figured I'd share my solution to problem 9 here.

The Problem
A Pythagorean triplet is a set of three natural numbers, a b c, for which,a^2 + b^2 = c^2
There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc.

The Solution
This is pretty basic and inefficient, but I decided to loop through a and b, calculating c from the difference.

#include
using namespace std;

int main () {

for(int a = 1; a < 1000; a++) {
for(int b = 1; b < 1000; b++) {
cout << "a: " << a << " b: " << b << " c: " << (1000 - a - b) << " a^2 + b^2: " << (a * a + b * b) << " c^2: " << (1000 - a - b) * (1000 - a - b) << endl;
if(a * a + b * b == (1000 - a - b) * (1000 - a - b)) {
return (0);
}
}
}
return (0);
}

There you have it, the program stops at a^2 + b^2 = c^2 where c = (1000 – a – b). I then took a*b*c to get the answer.

Ready to start a project?

Book a free consultation
Untitled UI logotext
Our work
About us
Blog
Careers
Submit a ticket
Agency Partnerships
Contact
© 2024 fjorge. All rights reserved.
Privacy