Prime function returns all values.

Ok here we are once again 30 minutes before class and my program is finally no longer getting any errors, but it's telling me that every value within the range is prime. If I failed to verbally describe that properly let me use this example output:

The prime numbers between 10 & 20 are:
11 12 13 14 15 16 17 18 19 20

...obviously that's not right, it should say:

The prime numbers between 10 & 20 are:
11 13 17 19

We're working on functions in class and the function is taking in the number to test (each number within the range is tested for "primeness") & a bool variable called 'prime' preset at 'false'. and sending back a true or false for 'prime'. True gets printed while false gets skipped.

I THINK (I've only been working in this for a few months now), that the function's "kill switch" that I'm trying to use to force it quit the function once a false is achieved is my problem. But I don't know ... all I know is that variable 'prime' is always going in 'false' and always coming out 'true'.

Any help, guidance, tips, tricks, insights, voodoo magic, or enchantments are appreciated as this is due in ... 26 minutes. Here's what I got so far:


// Kyle Norton
// Program #5
#include <iostream>
#include <cmath>
#include <iomanip>
#include <windows.h>
using namespace std;
// Super Awesome Cake Function of Awesomeness
void cake ()
{
cout << setfill ('-') << setw(76) << "-" << endl;
cout << " And Now For Cake ... " << endl;
Sleep(1500);
cout << " ... I promise it's not poisoned";
Sleep(1250);
cout << " ... beyond human tollerances" << endl;
Sleep(2000);
cout << endl << endl << "Humans like ethyl benzene, right?" << endl;
Sleep(1500);
cout << setfill ('-') << setw(76) << "-" << endl << endl << endl;
cout << " ,:/+/-" << endl;
cout << " /M/ .,-=;//;-" << endl;
cout << " .:/= ;MH/, ,=/+%$XH@MM#@:" << endl;
cout << " -$##@+$###@H@MMM#######H:. -/H#" << endl;
cout << " .,H@H@ X######@ -H#####@+- -+H###@x" << endl;
cout << " .,@##H; +XM##M/, =%@###@X;-" << endl;
cout << "X%- :M##########$. .:%M###@%:" << endl;
cout << "M##H, +H@@@$/-. ,;$M###@%, -" << endl;
cout << "M###M=,,---,.-%%H####M$: ,+@##" << endl;
cout << "@##################@/. :%##@$-" << endl;
cout << "M################H, ;HM##M$=" << endl;
cout << "##################. .=$M##M$=" << endl;
cout << "#################H..;XM##M$= .:+" << endl;
cout << "M####################@%= =+@MH%" << endl;
cout << "@#################M/. =+H#X%=" << endl;
cout << "=+M###############M, -/X#X+;." << endl;
cout << " .;XM###########H= ,/X#H+:," << endl;
cout << " .=+HM#######M+/+HM@+=." << endl;
cout << " ,:/%XM####H/." << endl;
cout << " ,.:=-." << endl << endl << endl;
}
// [NOTE TO SELF - DELETE BEFORE TURN IN] I'm sending in a false for 'prime' and it's always coming out true ... WTFBBQ!!11! This is infuriating!
// [NOTE TO SELF - DELETE BEFORE TURN IN] The issue resides here, the rest is functional, if main rec'd a false out of this funciton I have no doubt it would skip displaying that value ... focus your efforts here!
// Function - Prime Number Testing
void primetest (int numtest, bool& prime)
{
// Variables | Local --> Function: primetest
int count = numtest - 1;
// Logic - Primeness
while (count > 1)
{
if (numtest % count != 0)
{
prime = true;
}
else
{
prime = false;
return;// [NOTE TO SELF - DELETE BEFORE TURN IN] <==It's my 'killswitch' I'm virtually certain the issue has to be here. It's like the function continues on without reducing count to kill the function giving the function an ultimate value of true instead of keeping the false and killing the function. I've tried {count = count-count;} | return = 0; | return; God fucking damnit this is pissing me the hell off.
}
count--;
}
}
// **[BEGIN MAIN FUNCTION]**
int main()
{
// Variables | Local --> Main
int num1,num2,numtest;
bool prime = false;
// Input - Inital Data Set
cout << endl;
cout << " .,-:;//;:=," << endl;
Sleep (100);
cout << " . :H@@@MM@M#H/.,+%;," << endl;
Sleep (100);
cout << " ,/X+ +M@@M@MM%=,-%HMMM@X/," << endl;
Sleep (100);
cout << " -+@MM; $M@@MH+-,;XMMMM@MMMM@+-" << endl;
Sleep (100);
cout << " ;@M@@M- XM@X;. -+XXXXXHHH@M@M#@/." << endl;
Sleep (100);
cout << " ,%MM@@MH ,@%= .---=-=:=,." << endl;
Sleep (100);
cout << " =@#@@@MX., -%HX$$%%%:;" << endl;
Sleep (100);
cout << " =-./@M@M$ .;@MMMM@MM:" << endl;
Sleep (100);
cout << " X@/ -$MM/ . +MM@@@M$" << endl;
Sleep (100);
cout << ",@M@H: :@: . =X#@@@@-" << endl;
Sleep (100);
cout << ",@@@MMX, . /H- ;@M@M=" << endl;
Sleep (100);
cout << ".H@@@@M@+, %MM+..%#$." << endl;
Sleep (100);
cout << " /MMMM@MMH/. XM@MH; =;" << endl;
Sleep (100);
cout << " /%+%$XHH@$= , .H@@@@MX," << endl;
Sleep (100);
cout << " .=--------. -%H.,@@@@@MX," << endl;
Sleep (100);
cout << " .%MM@@@HHHXX$$$%+- .:$MMX =M@@MM%." << endl;
Sleep (100);
cout << " =XMMM@MM@MM#H;,-+HMM@M+ /MMMX=" << endl;
Sleep (100);
cout << " =%@M@M#@$-.=$@MM@@@M; %M%=" << endl;
Sleep (100);
cout << " ,:+$+-,/H#MMMMMMM@= =," << endl;
Sleep (100);
cout << " =++%%%%+/:-." << endl << endl << endl;
Sleep (100);
cout << " Welcome to Apeture Science's Prime Number Test v2" << endl << endl;
Sleep (100);
cout << " -----------------------------------------------------" << endl;
Sleep (100);
cout << " | Cake to be served @ the conclusion of the test |" << endl;
Sleep (100);
cout << " | Poison content of cake varies by particiapant |" << endl;
Sleep (100);
cout << " -----------------------------------------------------" << endl << endl << endl;
Sleep (100);
cout << "Enter an integer greater than 2 for the lower end of the range (0 => QUIT): ";
cin >> num1;
// Challenge - Quit Condition
while (num1 != 0)
{
// Test - Number Being Greater Than 2
while (num1 <= 2)
{
cout << setfill ('X') << setw(76) << "X" << endl;
cout << setfill ('X') << setw(38) << " ERROR " << setfill ('X') << setw(38) << "X" << endl;
cout << " | " << setw(4) << setfill( ' ' ) << num1 << " is not greater than 2. Please re-enter an integer greater than 2. |" << endl;
cout << setfill ('X') << setw(76) << "X" << endl << endl << endl;
cout << "Enter an integer greater than 2 for the lower end of the range (0 => QUIT): ";
cin >> num1;
cout << endl;
}
// Input - Upper Range Number
cout << "Enter an integer greater than " << num1 << " for the upper end of the range: ";
cin >> num2;
cout << endl;
// Test - Number Being Greater Than Low End Range Number
while (num2 <= num1)
{
cout << setfill ('X') << setw(76) << "X" << endl;
cout << setfill ('X') << setw(38) << " ERROR " << setfill ('X') << setw(38) << "X" << endl;
cout << " | " << setw(4) << setfill( ' ' ) << num2 << " is not greater than " << num1 <<". |" << endl;
cout << setfill ('X') << setw(76) << "X" << endl << endl << endl;
cout << "Enter an integer greater than " << num1 << " for the upper end of the range: ";
cin >> num2;
cout << endl;
}
// Output - Final
cout << "The Prime Numbers between " << num1 << " and " << num2 << " are:" << endl;
// Logic - Primeness
numtest = num1 + 1;
while (numtest <= num2)
{
primetest (numtest,prime); // <=== CALL TO FUNCTION: primetest
if (prime = true)
{
cout << numtest << " ";
}
else
{
cout << "";
}
numtest ++;
}
cout << endl << endl << endl;
// Challenge - Quit Condition
cout << "Enter an integer greater than 2 for the lower end of the range (0 => QUIT): ";
cin >> num1;
}
// Cakey Goodness
cake ();
// End
system("pause");
return 0;
}
in order to caculate a prime number say
bool primecheck(int i){
int n = i%2;
if(n == 1) return true;
else {
return false;
}
}

and remove the system("pause") command please, this just leaves a huge whole in your program.
Instead of comparing you are performing assignment in the statement

if (prime = true)
{
cout << numtest << " ";
}
else
{
cout << "";
}

It shall be

if (prime == true)

or even simply

1
2
3
4
5
6
7
8
if ( prime )
{
   cout << numtest << " ";
}
else
{
   cout << ""; 
}
Last edited on
vlad from moscow: Thank you again VLAD, I keep making that mistake. For some reason my brain doesn't want to register that whole "double equals" thing.

I like the way you wrote it { if ( prime ) } I'll use that. The program is still displaying all of the numbers within the range, not just the prime numbers. Any other suggestions would be great.


ui uiho: Thank you for the reply, but I'm not following your logic here, would you please elaborate?

Also removing the system("pause") is not possible as it is a piece of the original template & required on the files turned in to the class.


...and anyone else that has suggestions, feel free to share. I'm brickwalling here ...
closed account (G854izwU)
Here is what I use to check for primeness.

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
//-TheNewKids- code

int checkPrime (int numberToCheck) {
    bool prime = true;
    long long possibleFactor = 2;
    while (prime == true && possibleFactor < numberToCheck / 2) {

        if (numberToCheck % possibleFactor != 0) {

            prime = true;
            possibleFactor++;

        }
        else {

            prime = false;

        }

    }
    if (prime == true) {
        cout << numberToCheck << " Is a prime number." << endl;
    }
    prime = true;

}


Of course instead of having it print out that number is prime you could have it return true or false.

Hope this helps.

-TheNewKid-
BAHHH! .... that did it. It's so aggravating now that I see it written out. Putting the "kill switch" into the while loop for the function along with the counter.

void primetest (int numtest, bool& prime)
{
// Variables | Local --> Function: primetest
int count = numtest - 1;
bool primecheck;
// Logic - Primeness
while ( primecheck = true && count > 1 )
{
if (numtest % count != 0)
{
prime = true;
}
else
{
prime = false;
primecheck = false;
}
count--;
}
}

...and now it works properly. YEAH! I feel "special" now :)

Thanks to all for the help/advice!

Now time to get back to classwork. On a totally unrelated topic, if anyone knows where to get some high quality (free) texture images I'm all ears (mayang.com & cgtextures.com don't have what I need). I have to start building a city from the Firefly series in 3D Studio Max for my final project in another class.
the % operator returns the remainder of the division
for example

7%2 = 1 becuause 2 goes into 7 3 times so 3*2 = 6 7-6 = 1 <- that is your returned value

so all prime numbers are not divisible by 2 right? so the remainder is 1.
if it is divisible by 2 for example 8%2 = 0 which is not 1, and 8 is even
if you try it with 41 you do
41%2 = 1 because 2 goes into 41 20 times
so 20*2 = 40 41-40 = 1 <- doesnt that mean prime?
so

bool primecheck(int i){
int n = i%2; // will either equal 1 or 0
if(n == 1) return true; // if remainder is 1 than it is not even, therefore prime
else return false;//if not prime then it is even and therefore returns false for not // prime
}
Last edited on
so 20*2 = 40 41-40 = 1 <- doesnt that mean prime?


no it is not.

prime number is a number that is divided only by 1 and itself.
9%2 = 1 ; 2*4=8 ; 9 - 8 = 1; 9 is not a prime.
9%3 = 0 ; 3*3=9 ; 9 - 9 = 0;
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
#include <iostream>
using namespace std;

bool is_prime(int number)
{
	for (int i = 2; i < number; i++)
	{
		if (number%i == 0)
		{
			return false;
		}
	}
	return true;
}

int main()
{
	int number;
	
	cout << "Enter number: ";
	cin >> number;
	cout << endl;
	
	cout << "Number " << number;
	
	if (is_prime(number))
	{
		cout << " is ";
	}
	else
	{
		cout << " is not ";
	}
	
	cout << "a prime number." << endl;
	
	return 0;
}
upgraded :)
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
45
46
#include <iostream>
using namespace std;

bool is_prime(int number)
{
	for (int i = 2; i < number; i++)
	{
		if (number%i == 0)
		{
			return false;
		}
	}
	return true;
}

void print_primes(int number_1, int number_2)
{
	while (number_1 < number_2)
	{
		if (is_prime(number_1))
		{
			cout << number_1 << ", ";
		}
		number_1++;
	}
	
	return;
}

int main()
{
	int number_1, number_2;
	
	cout << "Enter first number: ";
	cin >> number_1;
	
	cout << "Enter second number: ";
	cin >> number_2;
	cout << endl;
	
	cout << "This is prime numbers: " << endl;
	print_primes(number_1, number_2);
	
	
	return 0;
}
Last edited on
class
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#include <iostream>
using namespace std;

class PrimeNumbers {
	public:
		PrimeNumbers() : first(NULL), last(NULL) {};
		~PrimeNumbers() { delete_all(); };
		void add_numbers(int, int);
		void get_primes();
		int sum_primes();
		void delete_all();
		
	private:
		struct Numbers {
			int number;
			Numbers * next;
		};
		Numbers * first, * last, * here;
		int first_number;
		void delete_one(int);
		void leave_primes();
};

void PrimeNumbers::add_numbers(int x, int y) {
	first_number = x;
	int two = 2;
	while ( two < y ) {
		if (first == NULL)
			first = last = here = new Numbers;
		else {
			last->next = new Numbers;
			last = last->next;
		}
		last->number = two;
		last->next = NULL;
		two++;
	}
	leave_primes();
}

void PrimeNumbers::leave_primes() {
	for (Numbers * i = here; i != NULL; i = i->next) {
		if (i->next != NULL and i->next->number % here->number == 0) {
			Numbers * temp;
			temp = i->next;
			i->next = i->next->next;
			delete temp;
		}
	}
	if (here->next != NULL) {
		here = here->next;
		leave_primes();
	}
}

void PrimeNumbers::get_primes() {

	for (Numbers * i = first; i != NULL; i = i->next) {
		if (i->number >= first_number)
			cout << i->number << ", ";
	}
}

void PrimeNumbers::delete_all() {
	while (first != NULL) {
		Numbers * i = first;
		first = first->next;
		delete i;
	}
	last = NULL;
	here = NULL;
}

int PrimeNumbers::sum_primes() {
	int sum = 0;
	for (Numbers * i = first; i != NULL; i = i->next) {
		if (i->number >= first_number)
			sum += i->number;
	}
	return sum;
}

int main () {
	//set up variables to hold user input
    int num_1, num_2;
    //ask for Input
    cout << "Type two integers, I will display all prime numbers in between these two numbers" << endl;
    cout << "Press enter after typing each number" << endl;
    cout << "First Number: ";
    //take input
    cin >> num_1;
    cout << "Second Number: ";
    cin >> num_2;
    
    PrimeNumbers numbers;
    numbers.add_numbers(num_1, num_2);
    numbers.get_primes();
    cout << endl;
    cout << "Sum of primes = " << numbers.sum_primes() << endl;
	return 0;
}
I cannot find another forum where functions are the topic. I need help with an assignment I have where I must code 4 functions basically. Can anyone help, please??
this is what I have and I'm extremely confused and lost.

#include <iostream>
#include <iomanip>
using namespace std;
double getWholeSale();
double getMark();
double calculateRetail();
void main()
{
cout<<fixed<<showpoint<<setprecision(2);
char choice;

double catchWSale=getWholeSale();
double catchMPercent=getMark();
double catchRetail=calculateRetail();

cout<<"The retail price is $"<<catchRetail<<"."<<endl;
cout<<" "<<endl;

do
{
cout<<"Do you want to do another markup? Enter 'Y' to continue, 'N' to stop."<<endl;
cin>>choice;
choice=toupper(choice);
}

while (choice!='N');
}
//**********
//This functiom gets wholesale cost
double getWholeSale()
{
double wholesale;
cout<<"Enter the item's wholesale cost: "<<endl;
cin>>wholesale;
while(wholesale<1)
{
cout<<"Enter a positive number for wholesale: "<<endl;
cin>>wholesale;
}
return wholesale;
}
//**********
//This function gets markup percentage
double getMark()
{
double markage;
cout<<"Enter the item's markup percentage: "<<endl;
cin>>markage;
while(markage<1)
{
cout<<"Enter a positive markup percentage: "<<endl;
cin>>markage;
}
return markage;
}
//**********
//This function calculates the retail price
double calculateRetail(double whole, double mrk)
{
/*double catchwhole=getWholeSale();
double catchpercent=getMark();*/
double retail;

retail=getWholeSale(1+getMark/100);
return retail;
}
create new topic for new question. And use source tags for code.
Topic archived. No new replies allowed.