Prime Number assignment basic c++ - c++

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.

Related

C++ How can I insert another loop or method to make 100 equivalent to 541?

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
}
}

using a user input in a loop and function

My program takes a user input, int n, and prints out the first n amount of prime numbers. This is working as intended
eg. if user inputs 8 as n. the program will print :
2 3 5 7 11 13 17 19
My problem is adding the function isPrime(n) (which is not allowed to be changed)
here is what i've tried but im just getting the output :
2 3 5 7 11 13 17 19 0 is not a prime number,
when it should read 2 3 5 7 11 13 17 19 8 is not a prime number
#include "prime.h"
#include <iostream>
int main()
{
int n;
std::cout << "Enter a natural number: ";
std::cin >> n;
for (int i = 2; n > 0; ++i)
{
bool Prime = true;
for (int j = 2; j < i; ++j)
{
if (i % j == 0)
{
Prime = false;
break;
}
}
if (Prime)
{
--n;
std::cout << i << " ";
}
}
if (isPrime(n))
{
std::cout << n << " is a prime number." << std::endl;
}
else
{
std::cout << n << " is not a prime number." << std::endl;
}
system("pause");
}
prime.h :
#ifndef PRIME_H_RBH300111
#define PRIME_H_RBH300111
bool isPrime(int);
#endif
#pragma once
the definition of isPrime(int)
prime.cpp :
#include <cmath>
#include "prime.h"
bool isPrime(int n)
{
if (n < 2)
{
return false;
}
else if (n == 2)
{
return true;
}
else if ((n % 2) == 0)
{
return false;
}
}
I cannot alter the .h file of prime.cpp
I just need the isPrime(n) function to work on the main() function code
the user input n, does not seem to be taking the number 8. but instead 0
giving me the output. 0 is not a prime number
rather than : n (8) is not a prime number
You are decrementing n in the loop. At the time the loop exits, the value of n is 0.
You can solve the problem by:
Using another variable to use in the loop.
Keeping a copy of the n and resetting the value of n after the loop exits.
Here's the second method:
int copyN = n;
for (int i = 2; n > 0; ++i)
{
...
}
n = copyN;
if (isPrime(n))
...
You are decrementing n in the for loop. The for loop has the condition 'n > 0', so you know n isn't > 0 when the loop finishes. You could either save the value of n in a different variable (i.e. "int nOrig = n;") and use that for the prime test, or use a different variable in the loop.

Print divisors in order using theta(n) efficiency

I'm struggling to implement this correctly. I want to create a function that determines all of the divisors of the user input userNum and outputs them to the user. When userNum = 16 i'm getting the output 1 16 2 8. I didn't expect the order to be correct, but i'm missing 4 and am struggling to figure out why. Any thoughts? I'm trying to do this in theta(sqrt(num)) efficiency.
void PrintDivisors(int num);
int main()
{
int userNum;
//Request user number
cout << "Please input a positive integer >=2:" << endl;
cin >> userNum;
PrintDivisors(userNum);
return 0;
}
void PrintDivisors(int num)
{
int divisorCounter;
for (divisorCounter = 1; divisorCounter < sqrt(num); divisorCounter++)
{
if (num % divisorCounter == 0 && num / divisorCounter != divisorCounter)
cout << divisorCounter << endl << num / divisorCounter << endl;
else if (num % divisorCounter == 0 && num / divisorCounter == divisorCounter)
cout << divisorCounter << endl;
}
}
Update: I have all the numbers printing, but still trying to determine how to print them in order while remaining within theta sqrt(n) efficiency
Change loop termination condition operation to <=, now you will observe 4.
Get rid of sqrt function call. Better use this loop
for (divisorCounter = 1; divisorCounter * divisorCounter <= num; divisorCounter++)
Make sure to check your edge conditions carefully.
What is sqrt(num)?
What is the largest divisorCounter that will pass the test in the for loop?
Would 4 pass the test?
I think if you look carefully at that line with these three questions in mind you will squash the bug.
For making it run in sqrt(n) time complexity:
For any n = a X b. either a<=sqrt(n) or b<=sqrt(n).
So if you can find all divisors in range [1,sqrt(n)] you can find other divisors greater than sqrt(n)
You can use a for loop to traverse numbers in range 1 to sqrt(n) and find all the divisors less than sqrt(n), which at the same time you can also use to find other numbers greater than(or equal to) sqrt(n).
Suppose a number i < sqrt(n) is divisor or n. In that case the number k = n/i will also be divisor of n. But bigger than sqrt(n).
For printing numbers in sorted order:
During finding divisors in range [1,sqrt(n)] print only divisor in range [1,sqrt(n)] You can use an array/vector to store numbers in range [sqrt(n),n] and print them after the for loop ends. Here is a sample code
vector<int> otherNums;
for(i=1;i*i<n;i++) {
if(num%i==0){
cout<<i<<endl;
otherNums.push_back(n/i);
}
}
if(i*i == n) otherNums.push_back(i);
for(i=(int)v.size() - 1 ;i>=0;i--)
cout<<otherNums[i]<<endl;
This is the solution I ended up using, which saves space complexity too. I was struggling to think of effective ways to loop over the solution in ascending order, but this one runs very fast and is nicer than appending to a vector or array or some weird string concatenation.
void printDivisors(int num)
{
for (int k = 1; k*k < num; k++)
{
if (num % k == 0)
cout << k << " ";
}
for (int d = sqrt(num); d >= 1; d--)
{
if (num % d == 0)
cout << num / d << " ";
}
cout << endl;
}

Can you explain this code to me and why is work c++ prime numbers

This code is to find the prime numbers from 3 to n, n being an input. this code works perfect but I need to understand it much more clearly mostly the part within the nested for loop.
#include <iostream>
using namespace std;
int main ()
{
cout << "Please enter a number: \n";
int inputtedNumber;
cin >> inputtedNumber;
cout <<"the primes between 3 and that number are: \n";
int candidate = inputtedNumber;
for (int i=3; i<candidate; i++)
{
bool prime=true;
for (int j=2; j*j<=i;j++)
{
if (i % j == 0)
{
prime=false;
break;
}
}
if(prime) cout << i << "\n";
}
system("pause");
return 0;
}
thank you!
The inner loop looks at each number from 2 to the square root of i, to see if i is divisible by that number. If i is divisible by j, then i%j will be zero. If it finds a divisor, then we know it's not prime and can stop looking.
There's no need to go beyond the square root since, if there is a divisor larger than that, there must also be a corresponding divisor smaller than that, which will already have been found by this loop.
This line is key.
if (i % j == 0)
The if block is executed if i is divisible by j, which implies that i is not prime.
for (int i=3; i<candidate; i++) // for every i between 3 and candidate
{
bool prime=true;
for (int j=2; j*j<=i;j++) // for every j between 2 and the square root of i
{
if (i % j == 0) // if there is an i that is evenly divisible by j
{
prime=false; // set the flag
break; // break the inner loop
}
}
if(prime) cout << i << "\n"; // if i was a prime (no j's were evenly divisible), print it
}

Simple Prime Numbers Program.... What is wrong with my code/script?

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;
}