### Euler Project Problem #3

Pages: 12
 ``1234567891011121314151617181920212223242526272829303132333435363738394041424344`` ``````#include #include using namespace std; int main() { long long int x; x = 0; while(x<=0) { cout << "Enter an integer greater than 0." << endl; cin >> x; } for(int k=2; k<(sqrt((double)x)); k++){ if(x % k == 0) { x = x/k; } } int count = 0; int temp = 0; int largestprime = 0; for(long long int i=(x/2); i>0; i--){ if(x % i== 0) { count = 0; for(long long int j=(i/2); j>0; j--){ if(i % j== 0) { count++; } } if(count == 1 && largestprime == 0) largestprime= i; } } if (largestprime != 0) { cout << largestprime << " is the largest prime multiple of " << x << endl;; } else { cout << x << " is a prime number." << endl; } system("PAUSE"); return 0; }``````

here is my finished program. it works right and fast.
I changed it by looking for the lowest factor at first and then dividing the big number by it. This cut it down to smaller size.
but my program still has major flaws.

if for example the user inputs a letter at first instead of a number, my program farts. I don't know how to control user input yet.
Chervil wrote:
The Python code looks useful. However, I'd suggest that false=True shows an unfortunate choice of variable name.

Fixed that.
 but my program still has major flaws. if for example the user inputs a letter at first instead of a number, my program farts. I don't know how to control user input yet.

You are solving a specific problem. You should only train your brain/learn some ways of solving specific problem. Your program shouldn't be The Best Program In The World; it just should do its job.

However, if you really do want to reuse this code later - your problem is that you take int as an input:
 ``123`` `````` long long int x; //code here cin >> x;``````

This way, if someone write text string - program will break. If you want to fix it, I suggest using sstream, although I think this is really unnecessary here, as we want program to work fast and we know what input should be.

PS. Oh, and one thing: Try to avoid
`system("PAUSE"); `

This is both not portable and not safe code.
Last edited on
Topic archived. No new replies allowed.
Pages: 12