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.
Related
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)
I am having some trouble understanding what a few lines mean in a code. I recently started learning C++ and picked up Bjarne Stroustrup's "Programming: Principles and Practice Using C++." There is a question in chapter 4 that was tripping me up, so I searched for a solution online to reference. Here is the code I ended up using in conjunction with the book:
#include "std_lib_facilities.h"
bool prime(vector<int> store, int number) {
for (int i = 0; i < store.size(); ++i)
if (number%store[i] == 0) return false; //line that I don't understand
return true;
}
int main() {
int max;
cout << "Please enter a maximum number you want checked for being prime or not.\n";
cin >> max;
vector<int> store;
for (int n = 2; n <= max; ++n)
if (prime(store, n)) store.push_back(n);
for (int n = 0; n < store.size(); ++n)
cout << store[n] << "\n";
keep_window_open();
return 0;
}
The objective of the code is to find all prime numbers below and equal to the user input, starting at 2. I understand everything that is going on in this code with the exception of one line (notated by the comment). What is the purpose of the int "number" on this line, and what mathematically is going on here? The aspect of it that is confusing me is "number" doesn't have a value, yet it is being divided by the value of the current element. If it equals zero, then theoretically the statement is false. Can someone please explain this to me? What does it have to do with finding prime numbers? I want to know what is happening at a basic level so that I may become a more efficient programmer and make my own solution. Thanks.
In the context of prime, store has prime numbers less than number so far.
number is a prime if and only if it's not divisible by any integers (beside 0 and 1) smaller than it
for (int n = 2; n <= max; ++n)
if (prime(store, n)) store.push_back(n);
Here the function is called repeatedly and the value of n is 2 at the beginning as
the for loop is iterating n starting from 2. This value of n is the value of number in the function body.
Hope that clears.
The aspect of it that is confusing me is "number" doesn't have a value
number does have a value: whatever value was passed in the call to prime(). In main(), prime() is called first with number=2, then number=3, ... up to number=max.
Other answers have addressed the mathematical reasoning behind the program.
If you want to understand how this program works - and inspecting the value of number during a call to prime(), as well as the call stack, is a great way to do that - I would suggest learning how to use a debugger such as gdb and poking around.
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.
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 8 years ago.
Improve this question
I was able to get this to run in 1.65 secs but I have a feeling that it could be faster. Doubles maybe?
#include<iostream>
using namespace std;
bool isPrime(int n) {
if(n%2 == 0 && n!=2) return false;
for(int i=3; i<n/2; i++) {
if(n%i == 0) return false;
}
return true;
}
int main() {
int num, i;
i=1000000007;
num = 1000000008;
for(;i<num; i++) {
if(isPrime(i)) cout << i << endl;
}
return 0;
}
You have no increment in the for loop in "isPrime". You have:
for(int i=3; i<n/2;)
You should have:
for(int i=3; i<n/2; i++)
Edit: since a commenter brought up optimizations, there are two things you can do to easily and greatly reduce the number of operations for large values of n.
The first is, as commented, to increment i by 2 (I am leaving my answer as is, since the point of the question was "why doesn't the code work" and not "how do I optimize the code," and it's easier for novice programmers to see the fix in its simplest form) since you already know you've eliminated all even numbers from the prior conditional.
The second is to only check up to the square root of n and not n divided by 2. The reason is as follows: if n is not prime, then there are two numbers greater than 1 and less than n that satisfy the condition
n = x * y
If both x and y are greater than the square root of n, then x * y is greater than n. Thus, if you haven't found any factors by time you iterate past the square root of n, n is prime.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I have to find closest numbers within two arrays and shows their difference. I am using a loop for that but it takes too much time. Do you know any way to make that algorithm faster?
#include <cmath>
#include <cstdio>
using namespace std;
long long int red, yellow, minimum = 1000000000, difference = 0;
long long int TC[100001], ZT[100001];
int main()
{
scanf("%d", &red);
for (int y = 0; y < red; ++y)
{
scanf("%d", &TC[y]);
}
scanf("%d", &yellow);
for (int yy = 0; yy < yellow; ++yy)
{
scanf("%d", &ZT[yy]);
}
for (int yyy = 0; yyy < red; ++yyy)
{
for (int i = 0; i < yellow; ++i)
{
difference = abs(TC[yyy] - ZT[i]);
if (difference == 0)
{
minimum = 0;
break;
}
else if (difference < minimum)
minimum = difference;
}
}
printf("%d \n", minimum);
}
This shoud be O(nlgn):
sort two lists
let i = 0, j = 0, minval = abs(list1[0] - list2[0])
as long as both lists have more items:
minval = min(minval, abs(list1[i] - list2[j])
if abs(list1[i + 1] - list2[j]) < abs(list1[i] - list2[j + 1])
increment i
else increment j
If you sort them, you can optimize algorithm to run much faster. When your both arrays are sorted, you can check one by one and compare them less than your current algorithm. Because you'll skip some of them, since you know they are sorted.
By the way, since you get the numbers from user, I suggest you to put numbers in sorted. Every time user enters a number, put the number in a place where numbers after it are bigger than it and numbers before it are less than it. To do such a thing, maybe using linked list is better idea (or easier).