Euler Project Problem #3

Pages: 12
Jun 5, 2013 at 12:56pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
#include <cmath>
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.
Jun 5, 2013 at 1:15pm
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.
Jun 5, 2013 at 6:09pm
closed account (18hRX9L8)
Chervil wrote:
The Python code looks useful. However, I'd suggest that false=True shows an unfortunate choice of variable name.

Fixed that.
Jun 5, 2013 at 7:49pm
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:
1
2
3
	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 Jun 5, 2013 at 7:50pm
Topic archived. No new replies allowed.
Pages: 12