I am wondering I can get some help at debugging or spotting the error in my program. The objective is to obtain user input and then display primes from input to zero, greatest prime to lowest.
Problem is the output includes the user input which may or may not be a prime number in itself, and repeats primes several times :(
Also, I am wondering why 2 isn't included?
My code:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int prime, division, input;
cout << "Please enter a number you wish to count down prime numbers from." << endl;
cin >> input;
for (prime = input ; prime >=2 ; prime-- )
{
for (division = 2 ; division < prime ; division++ )
{
if (prime % division == 0)
{
break;
}
else
{
cout << prime << " ";
}
}
}
return 0;
}
My output:
Please enter a number you wish to count down prime numbers from.
15
15 13 13 13 13 13 13 13 13 13 13 13 11 11 11 11 11 11 11 11 11 9 7 7 7 7 7 5 5 5 3
Thanks for those who help!
This is a program which tells whether the input number is prime or not.Any number is completely divisible by a number which is always less than it.
In case of prime numbers they are completely divisible by 1 and itself;
So i have used a counter variable which counts how many times a number is completely divisible by a number or numbers less than it.
The count will be always 2 for prime numbers and count will be more than two for others.
Count will be 1 for one...
So the program is as follows....
#include<iostream.h>
#include<conio.h>
class prime
{
int a;
public:
void check();
};
void prime::check()
{
cout<<"Insert a number";
cin>>a;
int count=0;
for(int i=a;i>=1;i--)
{
if(a%i==0)
{
count++;
}
}
if(count==1)
{
cout<<"\nOne is neither prime nor composite";
}
if(count>2)
{
cout<<"\nthe number is not prime its composite" ;
}
if(count==2)
{
cout<<"\nthe numner is prime";
}
}
void main()
{
clrscr();
prime k;
k.check();
getch();
}
To print all the prime numbers less than the number given as input; code is as follows:
#include<iostream.h>
#include<stdio.h>
#include<conio.h>
class prime
{
int a;
int i;
public:
void display();
};
void prime::display()
{
cout<<"Enter any number to find primes less than it";
cin>>a;
int count=0;
for(int j=a;j>=1;j--)
{
for(int i=1;i<=j;i++)
{
if(j%i==0)
{
count++;
}
}
if(count==2)
{
cout<<"\n"<<j;
}
count=0;
}
}
void main()
{
clrscr();
prime k;
k.display();
getch();
}
Try this code
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int prime, division, input;
cout << "Please enter a number you wish to count down prime numbers from." << endl;
cin >> input;
for (prime = input ; prime >=2 ; prime--)
{
boolean isDivisible = false;
for (division = 2 ; division < prime ; division ++)
{
if (prime % division == 0)
{
isDivisible = true;
}
}
if (isDivisible == false)
{
cout << prime << " ";
}
}
return 0;
}
For the first problem:
for 9, when division == 2, 9 % 2 ==1, so 9 is printed.Rather than You should have a flag value to denote if a number is prime or not, and print the number after you are sure it is prime.
For 2, EDIT: when prime == 2, and because division < prime is the condition that the inner loop get executed, the inner loop exits without running. All credits go to Marlon!
Check your inner for loop. Each run through the loop, your initializer gets reset to 2. Then you do Mod 2 on the suspected prime. If you get 0, all you really know is that the number is even. That might lead you to quickly say that the number isn't prime, but 2 mod 2 is 0, and 2 is prime. After the loop, "division" becomes 3. 15 mod 3 is 0. At that point, you break out of the loop, but 15 is NOT prime. Check your algorithm for determining primes. You could have it check against known primes, but that's not dynamic enough. There are other methods, one of which revolves around determining the suspected prime number's square root. Finally, you could do some good old (long) paper-pencil debugging.
Your inner loop is not correct. Its not printing primes, just odd numbers. It checks whether a number is divisible by 2 during first iteration and an even number will always be divisble. So the inner loop always breaks out if the number is even but it prints the number if odd and continues doing so till the loop breaks or terminates.
Lets try to get this with an example, the outer loop is at 9. The inner loop will check if its divisble by 2, since its not it'll print out the number and continue again. Next iteration will check whether its divisible by 3, since it is it'll break out.
And try using a function to check whether a number is prime that makes it more modular. Here's a little optimized version...
bool prime(int num)
{
int root = sqrt(num);
if(num == 2)
return true;
if(num%2 == 0)
return false;
for(int i=3;i<=root+1;i=i+2)
if(num % i == 0)
return false;
return true;
}
Related
My goal is to display the first list of prime numbers depending on user's input, when the user input 10, the program should display first 10 prime numbers which are 2 3 5 7 11 13 17 19 23 29. I'm thinking of having generated list from 2 which is the first prime number to 541 which is the 100th prime number then if the user input for example 100 then it will be equivalent to 2 upto 541. Will my algorithm works? currently I'm able to display prime numbers from 2 - 541 and stucked on implementing another loop for 1-100 input.
#include <iostream>
using namespace std;
int main() {
int N, counter, i, j, isPrime, n;
cout << "List of prime numbers from 1-100: ";
cin >> N; // if the user input 10 then the first 10 prime numbers are "2 3 5 7 11 13 17 19 23 29"
// list of prime from 2-541 (or first list from 1-100 prime numbers)
for (i = 2; i <= 541; i++) {
isPrime = 0;
for (j = 2; j <= i/2; j++) {
if (i % j == 0) {
isPrime = 1;
break;
}
}
if (isPrime == 0 && N != 101)
cout << i << " ";
}
}
Your current algorithm doesn't work, because N is never modified. If the user inputs 101 then nothing will be printed, because if (isPrime == 0 && N != 101) will always be false. If the user inputs anything else then it will always print the first 100 primes.
The key idea will be to count how many primes were found and break after the Nth prime. Or count down, how many primes we still need t ofind. The rough outline will be as follows:
for (i = 2; N > 0; i++) { // Loop as long as we need to find more primes
...
if(isPrime == 0) {
std::cout << ...
N--; // <- Found one prime, N-1 to go
}
}
i just started learning C++ , I am an art major (i know) and i started learning c++ from Alex Allain's jumping into c++ and in that book i have understood most of the stuff , I am currently stuck on prime number generator and i am having difficulty in the grasping the algothrim.I am not able to understand it after the first for loop
#include <iostream>
// note the use of function prototypes
bool isDivisible (int number, int divisor);
bool isPrime (int number);
using namespace std;
int main()
{
for (int i = 0; i < 100; i++) {
if (isPrime(i)) {
cout << i << endl;
}
}
}
bool isPrime(int number)// i don't understand from this point onward.
{
for (int i = 2; i < number; i++) {
if (isDivisible(number, i)) {
return false;
}
}
return true;
}
bool isDivisible(int number, int divisor)
{
return number % divisor == 0;
}
I humbly request anyone to help me understand this code step by step.
thank you so much
To understand the above code you first need to understand what are prime numbers.
A prime number is a number that is only divisible by 1 and itself.
For example:-
5 is divisible by 1 and 5 only (prime)
4 is divisible by 1, 2 and 4 (not prime)
So to check whether the number is prime or not we need to check whether it is divisible by any other number other than 1 and itself and if it is divisible by any other number then it is not prime.
So now let's understand this using the above code :-
bool isPrime(int number) {
for(int i=2;i<number;i++) { // this loops runs from 2 to number - 1
if(isDivisible(number,i)) { // this checks if the number is divisible by i if the number is divisible by i then the function isDivisible will return true
return false; // If the above condition is true that means the number is divisible by i and that means the number is not prime so we return false
}
}
return true; // and if the number is not divisible by any number between (2 to number-1) that means it is prime so we return true
}
for the second part of the code, we check whether the number is divisible by i
bool isDivisible(int number ,int divisor) {
return number % divisor == 0; /* it return true if number is divisible by divisor and false otherwise.
example:-
1. number = 4 divisor = 2
4%2 == 0 true
2. number = 5 divisor = 3
5%3 == 0 false
*/
}
So now let's see the whole code in working.
example:-
number = 5
isPrime(5)
we loop from 2 to 4
isDivisible(5,2) = false;
isDivisible(5,3) = false;
isDivisible(5,4) = false;
loop ends and we return true (the number is prime);
number = 4
isPrime(4)
we loop from 2 to 3
isDivisible(4,2) = true;
the above condition is true so we return false (the number is not prime);
Hope this helped you in understanding the above code
I have a function isPrime() that checks if a number if prime. On the first line the user enters an integer - the number of the tests. On the next lines are the numbers; If the number is not prime, 0 is written into a dynamic array (vector). Else - 1 goes to the array. However if I enter the following input:
3
21
41
7
The program outputs:
1
1
1
But 21 is obviously not a prime number since it has divisors 7 and 3. My question is what am I doing wrong?
#include <iostream>
#include <cmath>
#include <vector>
using namespace std;
vector <int> rez;
bool isPrime(int n)
{
for(int i=2; i<sqrt(n); i++)
{
if(n%i!=0)
{
return true;
}
else
{
return false;
}
}
}
int main()
{
int k,num;
cin>>k;
for(int i=0; i<k; i++)
{
cin>>num;
if(isPrime(num))
{
rez.push_back(1);
}
else
{
rez.push_back(0);
}
}
for(int i=0; i<rez.size(); i++)
{
cout<<rez[i]<<endl;
}
cout<<endl;
return 0;
}
if(n%i!=0)
{
return true;
}
else
{
return false;
}
This checks if the number is divisible by the first number in the loop, which is 2, and then exits the function, since there is a return statement in either clause of the conditional. This means that the loop only runs for 1 iteration. In the first case, you enter 21. 21 IS NOT divisible by 2, so the function returns true. The same goes for the other numbers. Change your conditional to:
if (num % i == 0)
{
return false;
}
This checks if the number is divisible by the current index you are checking, and if it IS divisible, it returns false. (Definition of prime numbers). You don't need an else statement, since you need to check if other numbers are possible factors of this number.
You implement the function wrongly. The first return is wrong. You check only devising by 2 and your function exits with true. You should continue the loop and return true after loop only.
Additionally you could make your function faster twice if you check devising by 2 separately, then start the loop from 3 with increasing the index by 2.
Here is my assignment:
A prime number is a number greater than 1 which is only evenly divisible by 1 and itself. For this assignment you will find which numbers from 2 to n (where n is a user-specified number) are prime.
Ask the user for a number, n, greater than 2. Keep asking for a number until a number greater than 2 is provided. Assume that the user will only enter numbers (that is, you do not need to check if a user enters text).
Use a loop to iterate on a variable, i, from 2 through n. For each iteration, check all numbers from 2 through i to determine whether the number is prime. If it is prime, print out i and the word "Prime".
Use the modulus operator, %, to determine if a number is prime
Here is what I have so far. It doesnt work. And I dont know why. please help, im a business student taking basic programming as an elective.
#include <iostream>
using namespace std;
int main()
{
int n;
int i;
int x;
while (n<=2)
{
cout << "Enter a number greater then 2: \n";
cin >> n;
for (x=n; x>=2; x--)
{
bool prime = false;
for (i=2; i<x; i++)
{
if (x%i==0)
{
prime = true;
}
}
if (prime==false)
{
cout << x << " Prime.\n";
}
}
}
return 0;
}
I didn't actually used your code because of indentication it was little bit of hard to read. But I wrote a new method for you. I suggest always divide your code into methods to make it more managable. You can call this in your main method
bool checkPrime(int number)
{ // input: num an integer > 1
// Returns: true if num is prime
// false otherwise.
int i;
for (i=2; i<number; i++)
{
if (number % i == 0)
{
return false;
}
}
return true;
}
And here is how can you call this method in the main:
int main()
{
int number;
cout << "Enter an integer (>1): ";
cin >> number;
if (checkPrime(number))
{
cout << number << " is prime." << endl;
}
else
{
cout << number << " is not prime." << endl;
}
// I think this is more convention than anything.
return 0;
}
It may not be the optimal program out there, but this should work:
#include <iostream>
using namespace std;
int main()
{
int n;
int i;
int x;
cout << "Enter a number greater then 2: \n";
cin >> n;
while (n<=2)
{
cout << "Enter a number greater then 2: \n";
cin >> n;
}
for (x=n; x>=2; --x)
{
for (i=2; i<x; ++i)
{
bool prime = true;
for (j=2; j<i/2; ++j)
{
if (i%j==0)
{
prime = false;
break;
}
}
if (prime)
{
cout << j << " Prime.\n";
}
}
}
return 0;
}
There are two easy means to go faster: first there is no need to test potential divisors that are too big (as pointed out by arne), and second, there is no need to test even numbers except 2.
Something like this:
#include <cassert>
bool is_prime(unsigned n)
{
if (n == 2)
return true;
if (n <= 1
|| n % 2 == 0)
return false;
for (int d = 3; d * d < n; ++d)
if (n % d == 0)
return false;
return true;
}
int main()
{
assert(!is_prime(0));
assert(!is_prime(1));
assert(is_prime(2));
assert(is_prime(3));
assert(!is_prime(4));
assert(is_prime(5));
assert(!is_prime(6));
assert(!is_prime(256));
assert(is_prime(257));
}
Of course, even faster is building a table of primes, and using this table as potential divisors, instead of every odd number. Makes sense if you have several numbers to check.
Please, say, why it let say you it does not work? Among others I get this output.
Enter a number greater then 2:
100
97 Prime.
89 Prime.
83 Prime.
79 Prime.
73 Prime.
71 Prime.
67 Prime.
61 Prime.
59 Prime.
53 Prime.
47 Prime.
43 Prime.
41 Prime.
37 Prime.
31 Prime.
29 Prime.
23 Prime.
19 Prime.
17 Prime.
13 Prime.
11 Prime.
7 Prime.
5 Prime.
3 Prime.
2 Prime.
But as int n; leaves n uninitialized, the while loop might not be entered.
I think the Answer 1 function checkprime(int number) can improved but purely on preformance basis, consider the fact that prime numbers cannot be even.So if add an extra check to see if (number % 2 == 0) will reduce a lot of iteration of the for loop, and for the remaining i think iterating the loop from 2 to 9 is enough rather than 2 to n. Too many iterations will slow you down on larger numbers.
I am trying to write a program that will tell you if the numbered entered is prime or not and will write all the prime numbers from 1 to 100 to a file and displays the numbers. This is what I have so far, but I'm lost.
bool isPrime(int);
int _tmain(int argc, _TCHAR* argv[])
{
int num, answer, choice, i, numb=1;
do
{
cout<< "Enter a number and I will tell you if it is prime or not."<<endl;
cin>> num;
if (isPrime(num))
cout<<num<<" is a prime number."<<endl;
else
cout<<num<< " is not a prime number."<<endl;
cout<<"Would you like the first 100 prime numbers displayed? (1 for yes and 2 for no)"<<endl;
cin>>choice;
if (choice == 1)
{
while(numb<=100)
{
i=2;
while(i<=numb)
{
if(num%i==0)
break;
i++;
}
if(i==num)
cout<<numb<<" is Prime"<<endl;
numb++;
}
}
else
{
cout<<"Would you like to run the program again? (1 for yes and 2 for no)"<<endl;
cin>>answer;
if (answer == 2)
{
exit(0);
}
}
while (answer == 1);
}
system("pause");
return 0;
}
bool isPrime (int number)
{
int i;
for (i=2; i<number; i++)
{
if (number % i == 0)
{
return false;
}
}
return true;
}
Really feel you are over-thinking this. You've done the hard part which was writing the isprime function.
Displaying the numbers is trivial, just write a for loop to go through the numbers and check which are prime, if a specific number is prime then print it to screen.
Then just add the write to file inside the loop for those numbers you print to screen.
Why not just reuse your isPrime()?
cout<<"Would you like the first 100 prime numbers displayed? (1 for yes and 2 for no) <<endl;
cin>>choice;
for (i=2; i < 100; i++)
{
if (isPrime(i)) cout << i << endl;
}
You're way over complicating things for yourself when printing all the primes from 1 to 100. Take a step back and think about what you want to do; cycle from 1 to 100, print the number if its prime.
for (int i = 1; i <= 100; ++i) {
if (isPrime(i))
cout << i << endl;
}
The while keyword of your do-while loop is on the wrong line. It should follow the closing brace. Compiler said around line 56 of the example code you posted.
After making changes to conform to standard C++, I compiled and ran the program. I chose the option to list all the primes up to 100. It is generous and displaying all the numbers, prime or not (hint: even numbers after 2 are not prime).
I inserted the following lines at the beginning:
#include <iostream>
using namespace std;
I changed the main function from _tmain to main since I'm not using Visual Studio compiler. Likewise the arguments too:
int main(int argc, char * argv[])
By the way, if you are not passing parameters to your program, you can simplify the declaration of main to:
int main(void)
Here is a modification to speed up your prime detector:
bool isPrime (int number)
{
int i;
if (number == 2)
{
return true;
}
if ((number % 2) == 0)
{
return false;
}
for (i = 3; i < number; i += 2)
{
if (number % i == 0)
{
return false;
}
}
return true;
}
This cuts down the number of checks by half because every even number after 2 is not prime, only odd numbers.