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
Related
first post here so hello world lol.
i starting learning c++ and doing some challenges. One i found is "find the next prime number" given an integer, make a function to find the next sequential prime number eg if given 12 return 13, if given 24 return 29, if given a prime return that. I dont understand why the following block of code doesnt work (my guess is that two of the conditions
int nextPrime(int num) {
while (num % 2 !=0 && num %3 != 0 && num %4 != 0 && num %5 != 0 && num %6 != 0 && num %7 != 0 && num %8 != 0 && num %9);
++num;
return num;
}
its a relatively easy task, but the fact i dont know why its not working bothers me more than the fact it isnt working. Any help you lovely internet people can provide is most welcome.
bool PrimeNumber(int n)
{for(int i=2;i<=n;i++){
if(n%i==0){
return false
}
return true
}
what you want to do is check each number starting from the next one to given number, see if it is prime. then just return the first one to be prime.
in nextPrime() function, we take a number starting from the next one to given number.
then in isPrime(), check if it is a prime.
if it is, return the number. else continue with the next one.
bool isPrime(int n)
{
// Corner case
if (n <= 1)
return false;
// Check from 2 to n-1
for (int i = 2; i < n; i++)
if (n % i == 0)
return false;
return true;
}
int nextPrime (int n){
for (int i=n+1; i<1000000; i++){
if (isPrime(i)) return i;
}
}
#include <bits/stdc++.h>
using namespace std;
//check if number is prime divide by all number less than sqrt(n)
bool isprime(int n){
for(int i=2;i*i<=n;i++){
if(n%i==0){
//not a prime return false then.
return false;
}
}// its a prime number.
return true;
}
int main() {
int n = 12345;
while(1){
if(isprime(n)){
cout << n <<endl;
// id its a prime number we are done break the loop.
break;
}
// increase n by 1. continue the loop untill the next prime.
n+=1;
}
return 0;
}
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.
I'm trying this program to find the sum of all the primes under two million, but for some reason I am coming up with a number far below what I should be expecting.
Here is my code. A co-working says I might not be catching all the primes with my program but he doesn't know C++ and I don't see how I could be missing them.
#include <iostream>
using namespace std;
int main()
{
int a = 500000;
int e = 0;
// this is an array to hold all the prime number i find,
// it's initialized to the arbitrarily high number of 500000
int list[a];
//here i am initializing the first members of my list to the first primes
list[0] = 2;
list[1] = 3;
list[2] = 5;
a = 3; // i set a = 3 to catch the next coming prime of 7
for (int c = 5; c < 2000000; c++)
{
// this bool is for prime catching,
// if d is false then the number will not be saved into the array
bool d = false;
// this bool is for an exit statement in the following iterative loop,
// if it's false the loop will exit
bool h = true;
for (int i = 0; list[i] < c/2 + 1 && h == true; i++)
{
// this checks to see if a number is evenly
// divisable by any of my primes so far
if (c % list[i] == 0)
{
d = false;
h = false;
}
}
if (d == true)
{
list[a] = c; // if i find a prime i save it into my array
e += c; // if i find a prime i sum it to my total
a++;
}
}
cout << e;
}
d is always and forever false. No code ever sets it to true.
Also, you need to start e at 10 (2 + 3 + 5).
Try this :)
#include <iostream>
using namespace std;
int main(){
bool prime;
int num = 200000;
int sum = 0;
for (int i=3; i<=num; i++){
prime = true;
for(int j=2; j<=i/2; j++){
if(i%j == 0) prime = false;
}
if(prime) sum+=i;
}
cout << sum;
}
In my opinion the most effective way to find if number is prime is to:
Check if number is less than 4 (<=3), then it is prime number. Assuming only positive-integers participate.
Otherwise, check if it is even number - then it is not a prime number.
If more than 3, and is not even - check it against all number from 3 to square-root of given number, skipping all evens in check. If it is multiple of any number, then it is not prime. Otherwise it is prime.
In C++ words:
bool IsPrime(unsigned int nCheck)
{
assert(nCheck>0);
if(nCheck<=3)
return true;
if(nCheck%2==0)
return false;
for(int nCounter = 3; nCounter <= sqrt(nCheck); nCounter += 2) // Skip evens
{
if(nCheck % nCounter == 0)
return false;
}
return true;
}
Any number is by 1 to square-root of that number. For example, 100, is divisible by max 10. Even it is divisible by, say 50, it is also divisible by 5. So, just check from 1 to 10.
I'm trying to figure out in c++ how to find all the prime numbers in a range (using 100 for now)
I'm not to concerned about performance, I'm starting out in c++ and trying to understand this program exercise from my book. I have my program I'm trying to use below but it keeps returning false. Any ideas? I've read through almost all of googles/bing's help as well as stack overflow. I can write code for it to work with inputting the number; just not looping through all numbers
any ideas on what i'm doing wrong?
#include <iostream>
using namespace std;
bool isPrime(long n);
int main()
{
int i;
//some vars
char emptyVar;
//first loop (to increment the number)
for (i = 0; i <= 100; i++)
{
//checking all numbers below 100
if (isPrime(i) == true)
{
//is true
cout << i << ", ";
}
else if (isPrime(i) == false)
{
//is false
cout <<"false , ";
}
}
cin >> emptyVar;
}
bool isPrime(long n)
{
long i =0;
//checks to see if the number is a prime
for (i = 2; i < n; i++) // sqrt is the highest possible factor
{
if ( n % i == 0) // when dividing numbers there is no remainder if the numbers are both factors
{
// is a factor and not prime
return false;
}
else if (n % i != 0 && i >= 100)
{
//is not a factor
return true;
}
}
}
The function isPrime does not have a return statement for every possible path of execution. For example, what does isPrime do, when n == 2?
Here's how a for loop works (in pseudo code). The general syntax is
for (initialiazion; condition; increment) {
body;
}
rest;
This can be translated into a while-loop:
initialiazion;
while (condition) {
body;
increment;
}
rest;
Especially, the condition is checked right after the intialization, before body is executed.
I suspect, you think that a for loop works like this:
initialiazion;
do {
body;
increment;
} while (condition);
rest;
i.e. the condition is checked after the first increment. But it doesn't.
It should return true if it's not a factor of EVERY i, not just the first one it encounters.
bool isPrime(long n)
{
long i =0;
//checks to see if the number is a prime
for (i = 2; i < n ; i++) // sqrt is the highest possible factor
{
if ( n % i == 0) // when dividing numbers there is no remainder if the numbers are both factors
{
// is a factor and not prime
return false;
}
}
return true;
}
Also in your case you doesn't make sense to search beyond i > n/2.
Of course you should give a look to the literature, the are really robust primality test algorithms.
Your isPrime function is incorrect. It should check all numbers and only then return true;
And this block wouldn't be ever called on your inputs:
else if (n % i != 0 && i >= 100)
{
//is not a factor
return true;
}
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;
}