C++ - Printing prime numbers till N [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
Question says:
You are given an integer N. You need to print the series of all prime numbers till N.
I want to know what's wrong with my code and suggestions will also be of great help.
#include<iostream>
using namespace std;
int main()
{
int N;
cin >> N;
int u;
for(int i = N; i > 0; i--)
{
u = 0;
for(int j = 2; j < N-1; j++)
{
if(i % j == 0)
{
u = 1;
}
}
if(u == 0)
{
cout << i << " ";
}
}
return 0;
}

First for future reference you should probably post that on code review, unless there is a specific problem then you should create a Minimal, Complete, and Verifiable post.
There is nothing inherently wrong other than you do not check that N>0 which could lead to an infinite loop, j should be going to i not N, and I think this would print 1 as a prime number which it is not. Here are some pointers:
Why are you going from N to 0? That seems a little counter intuitive compared from going from 2 to N (you can skip 1 since it is not prime)
If you are going to use a flag (u) then you should make it a bool which forces it to be either true or false
You do not need to do a flag, instead as soon as you find a divisor print the number and then break the inner loop like
for(j=2; j< N-1; j++){
if(i%j==0){
cout << i << " ";
break;
}
}
You do not need to have j go all the way to i, just the sqrt(i) since anything greater then the sqrt(i) that divides i must must be multiplied by some number smaller then the sqrt(i). So if i is not prime, then there must be a divisor below sqrt(i)

Related

Minimize Number- c++ [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
how can I Print the maximum possible number of operations that can be performed?
The operation is as follows: if all numbers are even then divide each of them by 2 otherwise, you can not perform any more operations.
First line contains a number N (1 ≤ N ≤ 200) number of elements.
Second line contains N numbers (1  ≤  A I  ≤  109).
Examples
Input
3
8 12 40
Output
2
Input
4
5 6 8 10
Output
0
I will write the cod in the comment cause I don't know how to put it here ..can you please edit it for me?
I know my code is wrong but I can't fix it so please explain it for me .
In this loop:
for(int i=0; i<n && 2<=n<=100 ;i++) {
2<=n<=100 is not doing what you mean. It evaluates to (2 <= n) <= 100) which is a different check.
You need to do:
2 <= n && n <= 100
You need to fix the other checks where you are doing this as well.
Also, since n is not being modified inside the loop, you can hoist this check out of the loop:
if (2<=n && n <=100) {
for(int i=0; i<n ;i++) {
and similarly for the other loops as well.
You are taking 'x' with n and m, but it has to be at end.
Also just use an 'index' variable to keep track of where to insert in your array. And then use the same 'index' while finding the 'x'.
#include <iostream>
using namespace std;
int main()
{
int a[100000],n,m,x;
cin>>n>>m;
bool flag=0;
int index =0;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++) {
cin >> a[index];
index++;
}
}
cin >>x;
for(int i=0;i<index;i++){
if(x==a[i]) {
flag = true;
}
}
if(flag==0){
cout<<"will not take number";
} else if(flag==1){
cout<<"will take number";
}
return 0;
}

Value of array index not increasing [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
Here if the condition occurs the value of i store in the array prime. But the index of the array is not increasing, all the values are storing at [0] index and destroy the previous value.
Tried all the other methods but didn't find anything.
I tried prime[x++] and prime[x+1], but they both didn't work for me. If someone gives me a solution then I'll be very thankful to you.
#include<iostream>
using namespace std;
int main()
{
int num = 20, prime[20], x;
for (int i = 1; i <= num; i++) {
if (i % 2 != 0) {
prime[x] = i;
}
}
for (int k = 1; k <= num; k++) {
cout << prime[x] << "\t";
}
}
You have the variable x un-initialized and you are using it, in the line
prime[x] = i;
assuming that it has been initialized. This invokes undefind behavior in your program and the result could not be predicted. Initialize it with the appropriate number to make the program to have a defined behavior.
Regarding prime numbers, see this SO post: Printing prime numbers from 1 through 100.
defining x as uninitialized is a undefined behaviour.
Initialize x as 0 (int x = 0;)
Try with bellow :
int x = 0;
for(int i=1; i<=num; i++){
if(i%2!=0){
prime[x] = i;
x++;
}
}
Now you have the number of prime array elements :
Now print prime array :
for(int k=0; k<x; k++){
cout << prime[k] << "\t";
}
The output (it seems your code detect odd numbers) :
1 3 5 7 9 11 13 15 17 19
Test the code online

Program runs in compiler but returns runtime error in online judge [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I'm trying to solve this problem on this online judge: https://a2oj.com/ladder?ID=3 (see problem below) using the following code. It runs successfully on the compiler but returns a runtime error on the online judge.
EDIT: Code after changing loop conditions
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
struct count {
int number;
int repetitions;
};
bool sortByNumber(const struct count &lhs, const struct count &rhs) {
return lhs.number < rhs.number;
}
int main() {
vector <int> input;
int n = 0;
do {
cin>>n;
input.push_back(n);
} while (n != 0);
struct count x[101] = {NULL};
for (int j = 0; j < input.size(); j++) {
int tracker = 0;
for (int z = 0; z < input.size(); z++) {
if (input[j] != x[z].number) {
tracker++;
}
}
if (tracker == input.size()) {
x[j].number = input[j];
}
}
sort(x, x+101, sortByNumber);
for (int y = 0; y < 101; y++) {
for (int w = 0; w < input.size(); w++) {
if (x[y].number == input[w]) {
x[y].repetitions++;
}
}
}
for (int v = 0; v < 101; v++) {
if (x[v].number != 0) {
cout << x[v].number << " " << x[v].repetitions << endl;
}
}
return 0;
}
I'm fairly new to programming so I apologize if the answer is obvious and I can't see it. I've researched causes of runtime errors and I can't see any memory leaks, logic errors, or divisions by zero. The only thing I can think of is that it's a segmentation fault caused by the many nested loops (this code uses a lot more memory and running time than the other programs I submitted to the online judge), but I can't think of another way to solve this problem. Any ideas, even just about where to look, would be very much appreciated.
EDIT: Problem
Problem Statement:
Amgad got a job as a Cashier in a big store, where he gets thousands of dollars everyday. As a cashier, he must count the amount of each dollar bill (banknote) he has at the end of each day.
Amgad wants you to help him by writing a computer program so Amgad can just enter the amount of each bill and you count each bill separately.
Input Format:
one or more positive numbers ending by zero each number is between 1 and 100 inclusive
Output Format:
print each number only once in one line followed by the number of repetitions
Sample Input:
100
20
5
2
10
20
5
5
20
100
10
2
2
10
5
0
Sample Output:
2 3
5 4
10 3
20 3
100 2
As #Component10 mentioned, your array is of a fixed size. Add an integer called count that increments every time a new number is popped out of the input. Change all the integer literal references to 8 to counter.
If input contains more than 101 elements, the conditions
if (tracker == 8) {
x[j].number = input[j];
}
and
if (input[j] != x[z].number) {
tracker++;
}
Are invoking undefined behavior for any j value above 100, due to out-of-bounds access of array x elements. Both z, and j are looped to input.size(), which can be higher than 101.
Undefined behavior can manifest itself in many ways. Runtime error is one of those possibilities.

C++ malloc(): memory corruption [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
I am currently going through a fibonacci practice problem on hackerrank and am having a malloc memory corruption error. This is the link to the problem I am doing:
https://www.hackerrank.com/contests/programming-interview-questions/challenges/fibonacci-returns/
Input is 0-10, each number separated by a new line.
For each input, the value at that point in the sequence is printed. It works for small inputs, but after 6 it gets the malloc error. It doesn't seem that the size of the sequence is an issue either, just how many are done in succession.
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
vector<int> bigFib(1);
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int x;
while(cin >> x){
if(bigFib.size()-1 >= x){
cout << bigFib[x] << endl;
}
else{
vector<int> fib(x);
fib[0] = 0;
fib[1] = 1;
for(int j = 2; j <= x; j++){
fib[j] = fib[j-1] + fib[j-2];
}
bigFib = fib;
cout << fib[x] << endl;
}
}
return 0;
}
I am pretty new to C++ and can't find the problem. Thanks for your time.
When you create std::vector of size N, you can access elements with index [0, N-1] - which is N elements. You create vector of size x and in your loop:
for(int j = 2; j <= x; j++){
fib[j] = fib[j-1] + fib[j-2];
}
and in this statement
cout << fib[x] << endl;
you try to access element with index equal to x, which is UB. If you do need to access index x create vector with at least x+1 size
In vector<int> fib(x); you declare a vector<int> that has x elements. Those elements are fib[0] through to fib[x - 1]. However, in for(int j = 2; j <= x; j++){ fib[j] = ... you assign to an element out of bounds.
Imagine if x is 1, then you'd expect your fib vector to contain only one element: fib[0]... yet your loop is assigning to fib[1]. Problem? Yup.
I reckon for(int j = 2; j <= x; j++){ should probably be for(int j = 2; j < x; j++){...
... and cout << fib[x] << endl; should be cout << fib[x - 1] << endl;

Relative prime numbers [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Two integers a and b are relatively prime if and only if there are no integers
x > 1, y > 0, z > 0 such that a = xy and b = xz.
I wrote program that determine how many positive integers less than n are relatively prime to n, but my program work too slow because sometimes number is too big. Can you fix my program.
My program should work for n<=1000000000
Here is my code:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
long int n;
int cntr = 0, cntr2 = 0;
cin >> n;
if (!n) return 0;
vector <int> num;
for (int i = 2; i < n; i++)
{
if (n % i != 0)
{
if (num.size()>0)
{
for (int j = 0; j < num.size(); j++)
{
if (i % num[j] != 0)
cntr2++;
}
if (cntr2 == num.size())
cntr++;
cntr2 = 0;
}
else
cntr++;
}
else
num.push_back(i);
}
cout << cntr + 1 << endl;
}
There are many things you can do to make this task go faster. Your approach is O(N^2), which strikes me as very poor.
A first pass at a simple faster version, would be to change your rel-prime test to using GCD.
for (int i = 2; i < n; i++)
{
if (GCD(i,n)==1) cntr++
}
cout << cntr + 1 << endl;
Using a standard Euler style GCD algorithm you can find easily off the web, this would be drastically better than what you are doing.
Try the iterative GCD funciton from here:GCD function in c++ sans cmath library
If this isnt good enough for your purposes (which it may not be) then I encourage you to search the web for one of several faster approaches. but, it may help in that searching to know that you are looking for the Euler Totient function: http://en.wikipedia.org/wiki/Euler%27s_totient_function
You need to do two things:
test fewer numbers
test them faster
Regarding point 1 - there are a number of things you can do. First - if n is even, there is no point in checking even numbers - so you can increment the "number to test" by 2. If n is divisible by 3, you can skip every third number. This is fairly easy to implement and will speed your code up for some numbers. The methos that Richard Plunkett outlined will help somewhat with point 2. I think there are much faster algorithms; I'll give it some thought.
Well to make it work for larger n values replace all int's with long int's and if you are using c++11 you could use long long int's if that still is not enough. To make it run faster you could just before the outer for loop add
/*reserve Some value that is close to the outcome*/
num.reserve(n/2);
this will help but not alot.