i am trying to find the nth prime number.
For example: input 1 - result 2 , input 2 - result 3, input 3-result 5...
My isprime function currently works but i couldnt figure it out, there must be something wrong, please help, thanks:)
/*
Finding the nth Prime Number
Yasin OSMAN
*/
//Including Libraries
#include <iostream>
using namespace std;
//Defining a global counter
int counter = 0;
/*
Defining Functions
*/
//isPrime Function (returns true if the given number is prime)
bool isPrime(int n) {
bool answer = true;
for (int i = 2; i < n; i++) {
if (n % i == 0) {
answer = false;
}
}
return answer;
}
int main() {
int userInput;
cout<<"Please indicate which prime number do you want to see: ";
cin>>userInput;
for(int i=0;i<=userInput;i++){
if(isPrime(counter)){
if(counter==userInput){
cout<<counter<<"th prime number is : "<<i<<endl;
}
counter++;
}
counter++;
}
return 0;
}
To improve the isPrime function:
numbers less than 2 won't be prime, so reject them first.
bool isPrime(int n) {
if (n < 2) return false; // add this line
bool answer = true;
for (int i = 2; i < n; i++) {
if (n % i == 0) {
answer = false;
}
}
return answer;
}
To improve the main function:
Increment the counter only if a prime number is found.
Count prime numbers found, then check the total number.
Check if the number, not the counter, is prime.
int main() {
int userInput;
cout<<"Please indicate which prime number do you want to see: ";
cin>>userInput;
for(int i=0, counter=0;counter<=userInput;i++){ // note: the global "counter" is shadowed here
if(isPrime(i)){
counter++;
if(counter==userInput){
cout<<counter<<"th prime number is : "<<i<<endl;
}
}
}
return 0;
}
Thanks to #MikeCAT
i changed my isPrime function for numbers that less than 2,
bool isPrime(int n) {
bool answer = true;
if(n<2){
answer=false;
return answer;
}
if(n>=2){
for (int i = 2; i < n; i++) {
if (n % i == 0) {
answer = false;
return answer;
}
}
return answer;
}
}
and i also made nthPrime a function,
int nthPrime(int n){
double i;
for(i=2;counter<n;i++){
if(isPrime(i)){
counter++;
}
}
return i-1;
}
and to display the result i used the following code :
int userInput;
cout<<"Please indicate which prime number do you want to see: ";
cin>>userInput;
cout<<counter<<"th prime number is : "<<nthPrime(userInput);
return 0;
Output Example : Please indicate which prime number do you want to see: 5
5th prime number is : 11
Related
The task was: Write a program that receives a number from the input and finds the first two prime numbers after it in c++.
I tried
#include <iostream>
// Check, if a number is prime and return true, if it is
bool isPrime(int value) {
bool isPrime = true;
// Try all potential values
for (int i = 2; i <= value / 2; ++i) {
if (value % i == 0) {
isPrime = false;
break;
}
}
return isPrime;
}
int main() {
// Read start value, check, if in OK range
if (int number{}; (std::cin >> number) and (number > 3))
{
int primeCounter = 0;
// Check for the next 2 prime values
while (primeCounter < 2) {
if (isPrime(number)) {
// Prime found
std::cout << number << '\n';
++primeCounter;
}
// Try next number
++number;
}
}
else
{
std::cout << "The input value is not ok\n";
}
}
But the answer was judged as wrong. What could be the reason?
Thank you for your kindness and help!
There are only some minor issues with the code:
The prime check function was not optimized. It worked, but now it is a little bit faster. But does not matter taht much.
The input range check was wrong and, because you wanted to have the primes after the input value. So one increment is necessary.
The corrected code looks like this:
#include <iostream>
// Check, if a number is prime and return true, if it is
bool isPrime(int value) {
// Special cases
if (value < 2) return false;
if (value == 2) return true;
if (value % 2 == 0) return false;
// Brute force
bool isPrime = true;
// Try all potential values
for (int i = 3; i*i < value / 2; i+=2) {
if (value % i == 0) {
isPrime = false;
break;
}
}
return isPrime;
}
int main() {
// Read start value, check, if in OK range
if (int number{}; (std::cin >> number) and (number > 0))
{
// need the next folowing 2 prime numbers
++number;
int primeCounter = 0;
// Check for the next 2 prime values
while (primeCounter < 2) {
if (isPrime(number)) {
// Prime found
std::cout << number << '\n';
++primeCounter;
}
// Try next number
++number;
}
}
else
{
std::cout << "The input value is not ok\n";
}
}
I'm writing a code to find the last prime number of a given range. Suppose the range is 1 to 50. Then the last prime no. I want to print must be 47. My idea was to maybe reverse the order of prime numbers in the range and then try printing only the first value. Again kinda like if my order was 1 to 50 then I would start printing from 47, 43 and so on and only print 47. But I'm stuck and not getting ideas on how I could do this. here's my code
int prime_bef(int n)
{
int check = 0;
for (int i = 1; i <= n; i++)
{
if (n % i == 0)
{
check++;
}
}
if (check == 2)
{
cout << n << " ";
}
return 0;
}
int main ()
{
int l;
int u;
cin >> l >> u;
for (int i = u; i >= l; i--)
{
prime_bef(i);
}
return 0;
}
You can just use exit() in the place you want to end the program, and it works fine in your case. But by far the best approach is returning a value to test for continuation, it is the most readable.
#include<iostream>
#include <stdlib.h>
using namespace std;
int prime_bef(int n)
{
int check = 0;
for (int i = 1; i <= n; i++)
{
if (n % i == 0)
{
check++;
}
}
if (check == 2)
{
cout << n << " ";
exit(0);
}
return 0;
}
int main ()
{
int l;
int u;
cin >> l >> u;
for (int i = u; i >= l; i--)
{
prime_bef(i);
}
return 0;
}
Same code using bool return type:
#include<iostream>
using namespace std;
bool prime_bef(int n)
{
int check = 0;
for (int i = 1; i <= n; i++)
{
if (n % i == 0)
{
check++;
}
}
if (check == 2)
{
cout << n << " ";
return true;
}
return false;
}
int main ()
{
int l;
int u;
cin >> l >> u;
for (int i = u; i >= l; i--)
{
if(prime_bef(i))
break;
}
return 0;
}
Here is a simple and efficient way to check if the number is prime. I am checking if the number is prime and when it is true I am printing the number and breaking the loop so that only 1 number is printed. You can always remove the break statement and print all prime numbers in range.
#include<iostream>
using namespace std;
bool isPrime(int n){
if(n==2)return true;
if(n%2==0 || n==1)return false;
for(int i=3; i*i<=n; ++i){
if(n%i==0){
return false;
}
}
return true;
}
int main (){
int l, u;
cin>>l>>u;
for (int i = u; i >= l; i--){
if(isPrime(i)){
cout<<i<<"\n";
break;
}
}
return 0;
}
I'll give you a hint... while you are iteratively checking for the prime nature of the number, also check whether the last prime number calculated in the loop is greater than the max term of the range and break the loop when the condition becomes false.
Here a C++17 approach :
#include <cmath>
#include <iostream>
#include <vector>
// type to use for storing primes
using prime_t = unsigned long;
// there is a way to determine an upper bound to the number of primes smaller then a maximum number.
// See : https://primes.utm.edu/howmany.html
// this can be used to estimate the size of the output buffer (vector)
prime_t pi_n(const prime_t max)
{
prime_t pi_n{ max };
if (max > 10)
{
auto ln_n = std::log(static_cast<double>(max));
auto value = static_cast<double>(max) / (ln_n - 1.0);
pi_n = static_cast<prime_t>(value + 0.5);
}
return pi_n;
}
// Calculate prime numbers smaller then max
// https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
auto calculate_primes(const prime_t max)
{
std::vector<bool> is_primes(max, true);
// 0, 1 are not primes
is_primes[0] = false;
is_primes[1] = false;
// sieve
for (prime_t n = prime_t{ 2 }; n < prime_t{ max }; ++n)
{
if (is_primes[n])
{
auto n2 = n * n;
for (prime_t m = n2; m < max; m += n)
{
is_primes[m] = false;
}
}
}
// avoid unnecessary resizes of vector by pre-allocating enough entries to hold result
prime_t n{ 0 };
std::vector<prime_t> primes;
primes.reserve(pi_n(max));
// add all prime numbers found by the sieve
for (const auto is_prime : is_primes)
{
if (is_prime) primes.push_back(n);
n++;
}
return primes;
}
int main()
{
const prime_t max{ 50 };
auto primes = calculate_primes(max);
// max prime is last one in container
auto max_prime = primes.back();
std::cout << "maximum prime number smaller then " << max << ", is " << max_prime << std::endl;
}
I'm trying to solve an algorithm for extracting a subsequence from an array. It should display the longest subsequence of prime numbers. I have written the whole algorithm but I still get an infinite cycle and I can't figure out where and why. I'm incrementing both indices and modifying the first index at the end, but it is still not working. Thanks a lot !!!
P.S: citire reads the array, prim detects if a number is prime or composed, afisare displays the subsequence and detSecv determines the longest subsequence.
#include <iostream>
#include <math.h>
using namespace std;
void citireSecv(int &n,int x[50])
{
cout<<"Da n: ";
cin>>n;
for(int i=1;i<=n;i++)
{
cout<<"Da un nr: ";
cin>>x[i];
}
}
int prim(int n)
{
int d=2;
while(d<=sqrt(n) && n%d!=0)
{
if(d==2)
d=3;
else
d=d+2;
}
if(d>sqrt(n)) return 1;
else return 0;
}
void afisare(int n,int x[50],int st,int f)
{
for(int i=st;i<=f;i++)
cout<<x[i]<<" ";
}
void detSecv(int n,int x[100],int &st,int &f)
{
st=1; f=0;
int i=1,j;
while(i<=n-1)
{
while(i<=n-1)
{
if(prim(x[i])==0 && prim(x[i+1])==0) i++;
}
j=i+1;
while(j<=n-1)
if(prim(x[j])==0 && prim(x[j+1])==0) j++;
if((j-i) > (f-st))
{
st=i;
f=j;
}
i=j+1;
}
}
int main()
{
int n,x[100],st,f;
citireSecv(n,x);
detSecv(n,x,st,f);
afisare(n,x,st,f);
return 0;
}
Input data:
n=2
First number is: 5
Second number is: 7
Probably just one of many issues with that code:
while(i<=n-1)
{
if(prim(x[i])==0 && prim(x[i+1])==0) i++;
}
j=i+1;
while(j<=n-1)
if(prim(x[j])==0 && prim(x[j+1])==0) j++;
There are two potential infinite loops here. If the conditions in the while don't return true on the first iteration, i (or j) will never get incremented, and you will have your infinite loop. You should almost always increment such variables outside of any conditions.
With a slight change in your code, you make it work, and one thing, you don't need to start array with index 1. you can always start with index zero.
for(int i=1;i<=n;i++)
{
cout<<"Da un nr: ";
cin>>x[i];
}
try to check for a case when no prime subsequence is found, while printing.
void detSecv(int n, int *x, int &start, int &end)
{
start = -1;
end = -1;
int i=0,j;
while(i < n) {
if(prim(x[i])) {
j = i + 1;
while(j < n)
if(prim(x[j])) j++;
else break;
} else {
i++;
continue;
}
if((j-i) > (end - start)) {
start = i;
end = j-1;
}
i=j+1;
}
}
This is a better way to verify if a number is prime or not
bool IsPrime(int number) {
int primeStep = 2;
double stepLimit = sqrt(number);
while(primeStep <= stepLimit)
{
if(number % primeStep == 0)
return false;
primeStep += 1;
}
return true;
}
And nou you can apply that function for each number in your array, and if it's prime , you add it in a new array like this:
void detSecv(int numberOfItems,int *arrayOfNumbers)
{
int arrayOfPrimeNumbers[50] = {};
int index = 0;
for(int i = 0; i < numberOfItems; i++)
{
if(IsPrime(arrayOfNumbers[i])){
arrayOfPrimeNumbers[index] = arrayOfNumbers[i];
index += 1;
}
}
int secondIndex = 0;
while(arrayOfPrimeNumbers[secondIndex] != 0)
{
cout << arrayOfPrimeNumbers[secondIndex] << " ";
secondIndex += 1;
}
}
Ok so I've already simplified/condense it while keeping the functionality,but im only doing C++ for a month and a half.Was at 100 lines of code.Is it possible to declare the variable in the functions arguement and then call them without passing values into the arguemnets?
#include <iostream>
#include <windows.h>
using namespace std;
int primeCheck10 (int j)
{
int count=0;
cout<<"Enter a number between 1 and 10___";
cin>>j;
if(j<1 ||j>10)
{
cout<<"Invalid Value\n";
return 0;
}
for(int i=2; i<j; i++)
{
if(j%i==0)
{
count++;
break;
}
}
if(count==0)
cout<<"Prime number\n";
else
cout<<"Not a Prime number\n";
}
int primeCheck100(int j)
{
int count=0;
cout<<"Enter a number between 1 and 100___";
cin>>j;
if(j<1 || j>100){
cout<<"Invalid Value\n";
return 0;
}
for(int i=2; i<j; i++)
{
if(j%i==0)
{
count++;
break;
}
}
if(count==0)
cout<<"Prime number\n";
else
cout<<"Not a Prime number\n";
}
int checkPrime1000(int j)
{
int count=0;
cout<<"Enter a number between 1 and 1000___";
cin>>j;
if(j<1 || j>1000){
cout<<"Invalid Value\n";
return 0;
}
for(int i=2; i<j; i++)
{
if(j%i==0)
{
count++;
break;
}
}
if(count==0)
cout<<"Prime number\n";
else
cout<<"Not a Prime number\n";
}
int main ()
{
system("pause");
return 0;
}
Yes, you can condense all the prime checking into a single function pretty easily. I'd change the structure of the code to just check whether a given number is prime, and return a bool to indicate whether it is or not:'
bool isprime(int n) {
int limit = sqrt(n)+1; // only need to check up to sqrt(n)
if (n == 2)
return true;
if (n == 1 || n % 2 == 0) // check if it's 1 or even
return false;
for (int i = 3; i <= limit; i += 2) // not even -- only check odd numbers
if (n % i == 0)
return false;
return true;
}
Then the code to get input and display results would be separate:
void primecheck(int limit) {
std::cout << "Please enter a number between 1 and " << limit;
int j;
std::cin >> j;
if (j<1 || j > limit)
std::cerr << "Invalid value";
static char const *labels [] = { "Not a prime number\n", "Prime number\n" };
std::cout << labels[isprime(j)];
}
It wouldn't be terribly difficult to make it even shorter than this, but we're reaching the point where it would probably end up less readable if you did so.
If I have unserstood correctly you then you are asking about default arguments. For example
#include <iostream>
void f( int i = 10 )
{
std::cout << "i = " << i << std::endl;
}
int main()
{
f();
}
You could just make one method... and add a bounds
int primecheck(int value, int bounds){
int count=0;
cout <<"Enter a number between 1 and " << bounds << "___";
cin>>value;
if(j<1 || value>bounds){
cout<<"Invalid Value\n";
return 0;
}
for(int i=2; i<value/2; i++)
{
if(value%i==0)
{
count++;
}
}
if(count==0)
cout<<"Prime number\n";
else
cout<<"Not a Prime number\n";
return count;
}
This alg is prob not the best way to check for primes though. for instance for(int i=2; i<j/2; i++) in your loop with optimize it. For example 32, 6x6 = 32, 2x16 = 32, 4x8 = 32. The highest number that can be divisible to j or value is half of it because 1 isn't considered under divisibility so the lowest number would be 2. Which is half.
This program is for a class. I am required to use two functions. These were the 3 errors listed:
error C2601: 'isPrime' : local function definitions are illegal
error C2601: 'reverse' : local function definitions are illegal
error C1075: end of file found before the left brace '{' at e.
Any other help and tips also greatly appreciate. Thanks!
/*
* 2/07/2013
* Computer Science II
* Homework #1
*/
//Purpose: Display first 'n' (user chosen) number if emirps to the console, five per line.
//Note: An "emirp" is a prime number that is also prime when reversed.
#include <iostream>
using namespace std;
int isPrime(int value); //Prototyle for "prime number function"
int reverse (int value2); //Prototype for "emirp function"
int main()
{
//Ask the user for a positive number
enter code here`enter code here`cout << "Please enter a positive number: ";
int n;
cin >> n;
//Reject negative value input
if ( n < 1)
{
cout << "INVALID NUMBER \n";
}
else
//Calculate all emirps up to 'n'.
for (int test = 0; test < n; test++)
{
int number = 2;
if (isPrime(number))
{
cout << "\n" << reverse(number) << "\t\t\t";
}
}
return 0;
}
int isPrime(int value)
{
//If value is prime, the remainder (count) will be zero twice--for 1 and itself.
int divisor = 1;
int count = 0;
int prime = 0;
if (value % divisor == 0)
{
count++;
++divisor;
}
if (count = 2)
{
int prime = value; //store prime value in new variable
}
return prime;
}
int reverse(int value2)
{
//reverse the number
value2*=10;
value2 = value2 %10;
value2/=10;
//same procedure as prime function
int divisor2 = 1;
int count2 = 0;
int emirp = 0;
if (value2 % divisor2 == 0)
{
{
count2++;
++divisor2;
}
if (count2 = 2)
{
int emirp = value2;
}
}
return emirp;
}
Problem with you syntax in reverse function
:
//same procedure as prime function
int divisor2 = 1;
int count2 = 0;
int emirp = 0;
if (value2 % divisor2 == 0)
{//if
{// ? why this
count2++;
++divisor2;
}//if