I am using this following code to find 10001th prime number but it is not running.
I am using devc++, but when I run this code, a blank screen comes up.
This is my Code:
#include<iostream>
#include<conio.h>
using namespace std;
int prime(int a)
{
int p=0;
for(int j=2;j<=a/2,p<=0;j++)
{
if(a%j==0)
{
p++;
}
}
if(p==0)
{
return 1;
}
else
return 0;
}
int main()
{
int i,c=0;
for(i=2;c<=10001;i++)
{
if(prime(1))
{
c++;
}
}
cout<<i;
return 0;
}
point 1:
you are passing if(prime(1)) argument 1 every time change this line to
if(prime(i))
point 2:
Change this line
for(int j=2;j<=a/2,p<=0;j++)
To
for(int j=2;(j<=a/2 && p<=0);j++)
Point 3:
Change this line
cout<<i;
To
cout<<i-1; // as at the end of `for` loop it will increment to `1` so print `i-1`.
First of all , I think you meant
if(prime(i))
instead of
if(prime(1))
Secondly, there are many gaps in this code .. First, you can verify if the number a divides by j with j taking a maximum value of sqrt(a) (using math.h library) , it would be faster when working with higher values.
Another thing, you said this is a code for finding the 10001th prime number not the number of prime numbers until 10001 and cout<<i; in the end doesn't make any sense, I think you meant cout<<c;
Let's look at each problem.
First, you need to use
if( prime(i) )
instead of
if( prime(1) )
I believe that was a typo on your part.
Second, as i is incremented after the for loop, you need to change
cout << i;
to
cout << i-1;
Third, the comma operator only executes the expression at the end. What you need here is &&. So change
for(int j = 2 ; j <= a/2 , p <= 0 ; j++)
to
for(int j = 2 ; j <= a/2 && p <= 0 ; j++ )
For more info on the comma operator, see Uses of C comma operator
Lastly, change
for( i = 2 ; c <= 10001 ; i++ )
to
for( i = 2 ; c < 10001 ; i++ )
Otherwise, you will get the 10002th prime number.
These should fix your problem.
Related
//Program to print sum of digits
#include <iostream>
using namespace std;
int main()
{
int n, m, sum = 0;
cin >> n;
for(int i = 0; i < n; i++)
{
m = n % 10;
sum += m;
n = n / 10;
}
cout << sum;
}
//Outputs
// Input = 123
// Output = 5 (should be 6)
// Input = 0235
// Ouput = 8 (should be 9)
Not printing the right answer when input no. is starting from 1 or 0.
By using While (n>0), it's giving the right output but I can't figure out why?
For starters the user can enter a negative number because the type of the variable n is the signed type int.
Thus neither loop either
for(int i = 0; i < n; i++)
or
while (n>0)
will be correct.
A correct loop can look like
while ( n != 0 )
And you need to convert each obtained digit to a non-negative value or you should use an unsigned integer type for the variable n.
As for this loop
for(int i = 0; i < n; i++)
then it entirely does not make a sense.
For example let's assume that n is initially equal to 123,
In this case the in the first iteration of the loop the condition of the loop will look like
0 < 123
In the second iteration of the loop it will look like
1 < 12
And in the third iteration of the loop it will look like
2 < 1
That means that the third iteration of the loop will not be executed.
Thus as soon as the last digit of a number is less than or equal to the current value of the index i the loop stops its iterations and and the digit will not be processed.
I have a task to print maximum int of matrix second line.
Example input:
3 2 (n, m)
-1 -2 <- 1 line
4 5 <- 2 line
2 6 <- 3 line
Max int in second line is 5. My program prints it. But if second line would be -100 -150, it not works. Sure it is because I have max = 0, but I don't know how to use it properly. I'm a student. Thanks in advance.
It is my code:
#include <iostream>
using namespace std;
int main() {
int n, m, max = 0;
cin >> n >> m;
int matrix[10][10];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> matrix[i][j];
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (matrix[1][j] > max) {
max = matrix[1][j];
}
}
}
if (max == 0 || n == 1) {
cout << "No";
} else {
cout << max;
}
}
And code works pretty good, unless there are negative numbers in second line
You are correct to suspect max = 0;. Why is that a problem? Well, first, perhaps you should try to explain to your rubber duck why it is correct. As you try to do so, you are likely to express an intent along the lines of "this value will not make it through the checks" or "this value will be replaced in the first iteration of the loop". Why? "Because matrix[1][j] > max will be true, so... Hold on, wasn't the problem when matrix[1][j] > 0 is false? So when max is 0, um... problem?"
The overall strategy is valid, but there is a requirement that max be initialized to a low enough value. There are two common strategies I can think of at the moment.
Use a value that is as low as possible for the type you are using. That is:
int max = std::numeric_limits<int>::lowest();
Use the value from the first iteration of the loop. No need to provide a value that is just going to be replaced anyway. There are some caveats for this, though. The most relevant for your example can be expressed as a question: what if there is no first iteration? (Perhaps there is only one row? Perhaps there are no columns?) Also, you would need to initialize max between your loops, after the matrix has been given values.
int max = (n > 1 && m > 0) ? matrix[1][0] : /* what value do you want here? */;
I wrote some code I wrote to print the powers of 2 up to like 39 or 40 idk but it dm. Anyway, I wrote it and rather than run the code and it not working because of a logic error, i ran the code and found that it works, and then spotted some logic errors showing that the code shouldn't work. Here is the code:
#include <iostream>
using namespace std;
int main()
{
int i = 1;
int j = 1;
int k = 1;
while (i < 40)
{
while (k < i)
{
j = j * 2;
cout << j <<"\n";
k++;
}
i++;
}
}
The output of this code is the powers of 2 up to about 2^40.
Why it shouldn't work: the second while loop shouldn't run because k = 1 and i = 1 so (k < i) is false. Also after each time the second while loop is completed, j and k should be reset to 1 in order for the logic to work however I don't resent them.
Can someone please explain why although all these logic errors, the code still works?
Also I tried this in python and got the same result.
Initial values:
i=1, k=1, j=1
Then we check i < 40. True. Then we check k < i. False. Then we increment i. Now:
i=2, k=1, j=1
Check i < 40. True. Check k < i. True. j=j*2 sets j=2. Print 2. Increment k. Check if k < i. False. Increment i. Now:
i=3, k=2, j=2
Following this, the inner loop executes at most once for every iteration of the outer loop. k < i is true until the k++ line, and then becomes true again at the i++ line.
I'm not sure whether I understand why there are nested loops here in the first place. It could be replaced with
while (i < 40) {
j = j * 2;
count << j << "\n";
i++
}
What was the intention of k?
#include <iostream>
using namespace std;
void bi(int a);
int main()
{
// here is the issue how do start a loop, where i want the answer from 16 to 31 numbers
int a=0;
cout<<"Baum-Sweet Sequence From 16 to 31 \n";
for(int j=a;j>16 && j<31;j++)
{
cout<<j;
}
bi(a);
system("Pause");
}
// Rest is working properly
void bi(int a)
{
int myArr[15],i=0,f=0,n=0;
for (int h = 0 ; h <= a; h++)
{
int num = h;
for (i = 0 ; i < 4 ; i++)
{
myArr[i] = num%2;
num = num/2;
}
for (int t = 0 ; t < 4 ; t++)
{
if (myArr[t]%2==0)
f++;
}
if (f%2==0)
cout << " = " << 1;
else
cout << " = " << 0;
cout <<endl;
}
}
i want to show the sequence from 16 to 31 decimal number but its not showing :\ could anyone help me out here
There is an error in the for loop.
The for loop has three parts separated by a semicolon.
for (INITIALIZATION; CONDITION; AFTERTHOUGHT)
{
// Source code for the for-loop's body
}
The first part initializes the variable (e.g. "int j = 16;" means that through the variable j you begin counting by 16);
The second part checks a condition and it quits the loop when false (e.g. j <=31 means that it quits the loop when j will have value 31);
The third one is performed once each time the loop ends and then repeats (e.g. j++ means that at each iteration of the loop j will be incremented by 1).
Each iteration will execute the code in the body of the for loop.
Considering that you want to call the bi function for each value from 16 to 31 your for loop body should include bi(j). Your main should be modified like the code below:
int main()
{
cout<<"Baum-Sweet Sequence From 16 to 31 \n";
for(int j=16;j<=31;j++)
{
cout<<j;
bi(j);
}
system("Pause");
return 0;
}
Your problem is that you set j to 0, but then make a condition for the loop that it will only execute if j (which is set to a), is bigger than 16.
Your first thing to do is to make the loop conditions this:
for (int j = 16; j <= 32; j++)
I need to find all the prime numbers from 2 to n using the Sieve of Eratosthenes. I looked on Wikipedia(Sieve of Eratosthenes) to find out what the Sieve of Eratosthenes was, and it gave me this pseudocode:
Input: an integer n > 1
Let A be an array of Boolean values, indexed by integers 2 to n,
initially all set to true.
for i = 2, 3, 4, ..., not exceeding √n:
if A[i] is true:
for j = i2, i2+i, i2+2i, i2+3i, ..., not exceeding n :
A[j] := false
Output: all i such that A[i] is true.
So I used this and translated it to C++. It looks fine to me, but I have a couple errors. Firstly, if I input 2 or 3 into n, it says:
terminate called after throwing an instance of 'Range_error'
what(): Range_error: 2
Also, whenever I enter a 100 or anything else (4, 234, 149, 22, anything), it accepts the input for n, and doesn't do anything. Here is my C++ translation:
#include "std_lib_facilities.h"
int main()
{
/* this program will take in an input 'n' as the maximum value. Then it will calculate
all the prime numbers between 2 and n. It follows the Sieve of Eratosthenes with
the algorithms from Wikipedia's pseudocode translated by me into C++*/
int n;
cin >> n;
vector<string>A;
for(int i = 2; i <= n; ++i) // fills the whole table with "true" from 0 to n-2
A.push_back("true");
for(int i = 2; i <= sqrt(n); ++i)
{
i -= 2; // because I built the vector from 0 to n-2, i need to reflect that here.
if(A[i] == "true")
{
for(int j = pow(i, 2); j <= n; j += i)
{
A[j] = "false";
}
}
}
//print the prime numbers
for(int i = 2; i <= n; ++i)
{
if(A[i] == "true")
cout << i << '\n';
}
return 0;
}
The issue is coming from the fact that the indexes are not in line with the value they are representing, i.e., they are moved down by 2. By doing this operation, they no longer have the same mathematical properties.
Basically, the value 3 is at position 1 and the value 4 is at position 2. When you are testing for division, you are using the positions as they were values. So instead of testing if 4%3==0, you are testing that 2%1=0.
In order to make your program works, you have to remove the -2 shifting of the indexes:
int main()
{
int n;
cin >> n;
vector<string>A;
for(int i = 0; i <= n; ++i) // fills the whole table with "true" from 0 to n-2
A.push_back("true");
for(int i = 2; i <= sqrt(n); ++i)
{
if(A[i] == "true")
{
for(int j = pow(i, 2); j <= n; j += i)
{
A[j] = "false";
}
}
}
//print the prime numbers
for(int i = 2; i <= n; ++i)
{
if(A[i] == "true")
cout << i << '\n';
}
return 0;
}
I agree with other comments, you could use a vector of bools. And directly initialize them with the right size and value:
std::vector<bool> A(n, false);
Here you push back n-1 elements
vector<string>A;
for(int i = 2; i <= n; ++i) // fills the whole table with "true" from 0 to n-2
A.push_back("true");
but here you access your vector from A[2] to A[n].
//print the prime numbers
for(int i = 2; i <= n; ++i)
{
if(A[i] == "true")
cout << i << '\n';
}
A has elements at positions A[0] to A[n-2]. You might correct this defect by initializing your vector differently. For example as
vector<string> A(n+1, "true");
This creates a vector A with n+1 strings with default values "true" which can be accessed through A[0] to A[n]. With this your code should run, even if it has more deficits. But I think you learn most if you just try to successfully implement the sieve and then look for (good) alternatives in the internet.
This is painful. Why are you using a string array to store boolean values, and not, let's say, an array of boolean values? Why are you leaving out the first two array elements, forcing you to do some adjustment of all indices? Which you then forget half the time, totally breaking your code? At least you should change this line:
i -= 2; // because I built the vector from 0 to n-2, i need to reflect that here.
to:
i -= 2; // because I left the first two elements out, I that here.
// But only here, doing it everywhere is too annoying.
As a result of that design decision, when you execute this line:
for(int j = pow(i, 2); j <= n; j += i)
i is actually zero which means j will stay zero forever.