Here's a c++ program i tried to write for the above question.Our teacher told us to use a for loop.
void main()
int A[30],B[30],m,n,i,j,x,z;
cout<< "enter two numbers";
cin>>m>>n;
for(i=1,j=0;i<=m,j<30;i++,j++)
{
if(m%i==0)
{ A[j]=i;
z=j;
}
}
for(i=1,j=0;i<=n,j<30;i++,j++)
{
if(n%i==0)
{ B[j]=i;
x=j;
}
}
for(i=z;i>=0;--i)
{
for(j=x;j>=0;--j)
{
if(A[i]==B[j])
{ cout<<"gcd="<<A[i];
}
}
}
}
The output displays " Enter two numbers:" and when i entered 15 and 3, the result i got was a blinking cursor. Working through the program, I realised that the divisors for each number when stored in the arrays of A and B were not stored continuously or had gaps in between. If there isn't anything in the memory for say A[11], what happens when you check it against another variable with a number? Can somebody please modify this to make it work and tell me what's wrong? I am new to programming, so excuse my program if it is clumsy.
Andreas has pointed out that there are other ways to achieve the goal of finding the gcd, but the point of the exercise is to get a better handle on some basic programming constructs. So lets go with your approach.
Your idea is to compute the two lists of divisors and then compare them. As you say, having a list with gaps in makes this harder.
So adapt your loop, only increment the storage index when you've stored something
for(i=1,j=0;i<=m && j<30;i++) // need the && here; a comma means something different
{
if(m%i==0)
{ A[j++]=i;
z=j;
}
}
Second, you have a typo you're not storing in B, so fix that
for(i=1,j=0;i<=n && j<30;i++)
{
if(n%i==0)
{ B[j++]=i; //B here not A
x=j;
}
}
That should help.
Try this:
int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
As taken from here: https://codereview.stackexchange.com/questions/66711/greatest-common-divisor
Related
I am trying to find the third highest number in the array with O(n) space and time complexity.
MY program is obviously wrong but that is not the problem.
My for loop in the thirdhighestnum function seem to running only 2 times. I can't seem to find the reason for it. Can anyone help me. Sorry for such basic question I am a beginner here.
#include<iostream>
using namespace std;
int thirdhighestnum(int a[],int size)
{
cout<<" "<<size<<endl;
int first=a[0],second=0,third=0;
for(int i=1;i<size;i++)
{
cout<<a[i]<<";"<<endl;
if(a[i]>first)
{
first=a[i];
if(a[i+1]>first)
{
second=first;
first=a[i+1];
if(a[i+2]>first)
{ third=second;
second=first;
first=a[i+2];
}
}
cout<<i<<endl
return third;
}
}
}
int main()
{ int num,a[10];
cout<<"Enter the elements in the array"<<endl;
for(int i=0;i<10;i++)
cin>>a[i];
cout<<"Third highest number is "<<thirdhighestnum(a,10)<<endl;
return 0;
}
It's the location of your return third statement. The moment any number is larger than the first number, it exits the thirdhighestnum function and returns a value. Put it outside your for loop and it should be fine.
Actually it is executing only one time i.e. the first iteration only. When i=1 then it prints a[1] i.e. 2; after that it prints i i.e. 1 so it appears as 2;1 here you think it is printing 2 numbers.
The main problem is your return third statement which terminates your for loop in first iteration only.
This is known as nth_element and library function can do this for you.
As for why your code fails, there is a flaw in your logic
for(int i=1;i<size;i++)
{
// some code
if(a[i]>first)
{
// some more code
cout<<i<<endl
return third;
}
}
So your code exits the first time a[i] is greater than first.
[edit - After reading comments]
The generic name for this type of algorithm is a QuickSelect. It is unlikely you will find a faster algorithm, as this has been the subject of years of academic study.
I am trying to find the 1D peak through Divide and Conquer technique in this particular question,
my program even though it runs,
but at the time of giving the final output it says that there has been some problem with the execution,
I have got the answer from a different method, but I would like to know where am I at fault here.
#include<iostream>
using namespace std;
int a[8];
class pg1
{
public:
int func(int n)
{
if(a[n] <= a[n+1])
{
func(n++);
}
else if(a[n] <=a [n-1])
{
func(n--);
}
else
{
return n;
}
}
};
int main()
{
pg1 ob;
for(int i=0;i<8;i++)
{
cin >> a[i];
}
int x = ob.func(4);
cout << endl << x;
return 0;
}
Input-
5
6
8
5
4
3
6
4
Errors are-
1D Peak.exe has stopped working.
A problem caused the program to stop working correctly.Windows will close the program and notify you aif a solution is available.
End Result-
Process Exited with return value 3221225725
Don't use postincrement and similar in function calls.
Here's the problem condensed down to a really simple piece of code
#include <iostream>
int test(int n){
if(n == 1){
std::cout << "Function called!";
return test(n++);
}else{
return 0;
}
}
int main() {
test(1);
return 0;
}
Before you run this, ask yourself what you expect to happen here. Did it do what you thought?
When you run this you'll see that the code doesn't terminate properly. The output shows the function gets called infinitely many times, eventually the stack runs out of space and the program crashes.
You can see this code in action here: http://ideone.com/QL0jCP
In your program you have the same problem:
int func(int n)// say n = 4
{
if(a[n] <= a[n+1])//say this is true
{
func(n++); //this calls func(4) THEN increments n afterwards
}
This calls func with the same value over and over.
The solution is to not use postincrement or postdecrement in your function calls. These create hard to diagnose bugs as you have seen in this question. Just a simple func(n+1) is all you need. If you needed to use the variable later then just create an explicit variable to do that, it's much cleaner coding style (as this problem you ran into here shows).
After you fix this you'll need to fix your array bounds checking.
if(a[n] <= a[n+1])
If n is the last spot in the array you suddenly are trying to access one place past the end of the array, if you are lucky you get a segfault and a crash, if you are unlucky you get some bug that messes up your system that is hard to find. You want to check the values are valid.
My code is:
#include<stdio.h>
void main(void)
{
float timeLeavingTP;
int transitNumber;
float transitTime;
printf("Please enter the time leaving TP.\n");
scanf_s("%f",&timeLeavingTP);
printf("Please enter bus number.\n");
scanf_s("%d",&transitNumber);
if(timeLeavingTP==1.00)
{
if(transitNumber==27)
{
transitTime=1.56;
}
else if(transitNumber==8);
{
transitTime=1.39;
}
}
if(timeLeavingTP==6.30)
{
if(transitNumber==27)
{
transitTime=7.32;
}
else if(transitNumber==8)
{
transitTime=7.29;
}
printf("The time reached home is %f\n",transitTime);
}
}
After debugging i got
Please enter the time leaving TP
1.00
Please enter bus number
27
Please enter to continue...
My question is How do i adjust the program to make it look like the one below instead. What kind of error did i commit?
Please enter the time leaving TP
1.00
Please enter bus number
27
The time reached home is 1.56
Thanks for the help in advance!
Hi guys after including == i still got the same for my debugging? Is there something else that i did wrong?
Part 1: = vs ==
Note that:
if(timeLeavingTP=1.00)
Does not do what you expect. It assigns timeLeavingTP with 1.00.
You probably want:
if(timeLeavingTP==1.00)
Additionally, note that this error occurs 6 times in your program.
Part 2: comparing floating point numbers
Your code might work in this case, but I'm not 100% sure if it will or not. It's often difficult to directly compare 2 floating point numbers, because of the inaccuracy of storing them (for example, 0.1 is usually not representable in floating point).
Most people solve this problem in one of a few ways:
Test a range around the number.
Convert to some fixes width format. Perhaps you could store the number as an integer, knowing that it's representation is actually 0.01 * the stored number.
In this case, you could actually just store the information as strings, and compare those.
Part 3: conditionals
To write a proper conditional, it should look like:
if (condition) {
...
} else if (condition) {
...
} else if (condition) {
...
} else {
...
}
You can certainly nest conditionals as well:
if (condition) {
if (condition) {
...
} else {
...
}
} else if (condition) {
...
}
Your code, for example, messes this up when you do:
}
else(transitNumber=8);
{
transitTime=1.39;
}
Note that the else statement does not accept a conditional after it.
Part 4: excessive semicolons
Additionally, note that after the else and if statements there are no semicolons. The semicolons only appear within the braces. So this statement:
if(timeLeavingTP=6.30);
While semantically valid, does not do what you expect. You actually want to remove that semicolon.
if(timeLeavingTP == 1.00)
{
if(transitNumber == 27)
{
transitTime=1.56;
}
else if(transitNumber == 8)
{
transitTime=1.39;
}
}
else if(timeLeavingTP == 6.30)
{
if(transitNumber == 27)
{
transitTime == 7.32;
}
if(transitNumber ==8)
{
transitTime=7.29;
}
}
printf("The time reached home is %f\n",transitTime);
}
if(transitNumber=27)
{
transitTime=1.56;
}
else(transitNumber=8);
{
transitTime=1.39; //this line is executed all the time
}
This code is completly invalid!
First, you do not compare anything... transitNumber = 27 is an assignment.
Second else(transitNumber=8); again this is an assignment and it should be else if(...). Also ; at the and means that transitTime = 1.39(inside bracket) will always happen, even if transitNumber != 8
Change
if(timeLeavingTP=1.00)
to
if(timeLeavingTP==1.00)
so that you can compare timeLeavingTP correctly.
I made this algorithm, i was debugging it to see why it wasnt working, but then i started getting weird stuff while printing arrays at the end of each cycle to see where the problem first occurred.
At a first glance, it seemed my while cycles didn't take into consideration the last array value, but i dunno...
all info about algorithm and everything is in the source.
What i'd like to understand is, primarily, the answer to this question:
Why does the output change sometimes?? If i run the program, 60-70% of the time i get answer 14 (which should be wrong), but some other times i get weird stuff as the result...why??
how can i debug the code if i keep getting different results....plus, if i compile for release and not debug (running codeblocks under latest gcc available in debian sid here), i get most of the times 9 as result.
CODE:
#include <iostream>
#include <vector>
/*void print_array
{
std::cout<<" ( ";
for (int i = 0; i < n; i++) { std::cout<<array[i]<<" "; }
std::cout<<")"<<std::endl;
}*/
///this algorithm must take an array of elements and return the maximum achievable sum
///within any of the sub-arrays (or sub-segments) of the array (the sum must be composed of adjacent numbers within the array)
///it will squeeze the array ...(...positive numbers...)(...negative numbers...)(...positive numbers...)...
///into ...(positive number)(negative number)(positive number)...
///then it will 'remove' any negative numbers in case it would be convienent so that the sum between 2 positive numbers
///separated by 1 negative number would result in the highest achievable number, like this:
// -- (3,-4,4) if u do 'remove' the negative number in order to unite the positive ones, i will get 3-4+4=3. So it would
// be better not to remove the negative number, and let 4 be the highest number achievable, without any sums
// -- (3,-1,4) in this case removing -1 will result in 3-1+4=6, 6 is bigger than both 3 and 4, so it would be convienent to remove the
// negative number and sum all of the three up into one number
///so what this step does is shrink the array furthermore if it is possible to 'remove' any negatives in a smart way
///i also make it reiterate for as long as there is no more shrinking available, because if you think about it not always
///can the pc know if, after a shrinking has occured, there are more shrinkings to be done
///then, lastly, it will calculate which of the positive numbers left is highest, and it will choose that as remaining maximum sum :)
///expected result for the array of input, s[], would be (i think), 7
int main() {
const int n=4;
int s[n+1]={3,-2,4,-4,6};
int k[n+1]={0};
///PRINT ARRAY, FOR DEBUG
std::cout<<" ( ";
for (int i = 0; i <= n; i++) { std::cout<<k[i]<<" "; }
std::cout<<")"<<std::endl;
int i=0, j=0;
// step 1: compress negative and postive subsegments of array s[] into single numbers within array k[]
/*while (i<=n)
{
while (s[i]>=0)
{
k[j]+=s[i]; ++i;
}
++j;
while (s[i]<0)
{
k[j]+=s[i]; ++i;
}
++j;
}*/
while (i<=n)
{
while (s[i]>=0)
{
if (i>n) break;
k[j]+=s[i]; ++i;
}
++j;
while (s[i]<0)
{
if (i>n) break;
k[j]+=s[i]; ++i;
}
++j;
}
std::cout<<"STEP 1 : ";
///PRINT ARRAY, FOR DEBUG
std::cout<<" ( ";
for (int i = 0; i <= n; i++) { std::cout<<k[i]<<" "; }
std::cout<<")"<<std::endl;
j=0;
// step 2: remove negative numbers when handy
std::cout<<"checked WRONG! "<<unsigned(k[3])<<std::endl;
int p=1;
while (p!=0)
{
p=0;
while (j<=n)
{
std::cout<<"checked right! "<<unsigned(k[j+1])<<std::endl;
if (k[j]<=0) { ++j; continue;}
if ( k[j]>unsigned(k[j+1]) && k[j+2]>unsigned(k[j+1]) )
{
std::cout<<"checked right!"<<std::endl;
k[j+2]=k[j]+k[j+1]+k[j+2];
k[j]=0; k[j+1]=0;
++p;
}
j+=2;
}
}
std::cout<<"STEP 2 : ";
///PRINT ARRAY, FOR DEBUG
std::cout<<" ( ";
for (int i = 0; i <= n; i++) { std::cout<<k[i]<<" "; }
std::cout<<")"<<std::endl;
j=0; i=0; //i will now use "i" and "p" variables for completely different purposes, as not to waste memory
// i will be final value that algorithm needed to find
// p will be a value to put within i if it is the biggest number found yet, it will keep changing as i go through the array....
// step 3: check which positive number is bigger: IT IS THE MAX ACHIEVABLE SUM!!
while (j<=n)
{
if(k[j]<=0) { ++j; continue; }
p=k[j]; if (p>i) { std::swap(p,i); }
j+=2;
}
std::cout<<std::endl<<"MAX ACHIEVABLE SUM WITHIN SUBSEGMENTS OF ARRAY : "<<i<<std::endl;
return 0;
}
might there be problems because im not using vectors??
Thanks for your help!
EDIT: i found both my algorithm bugs!
one is the one mentioned by user m24p, found in step 1 of the algorithm, which i fixed with a kinda-ugly get-around which ill get to cleaning up later...
the other is found in step2. it seems that in the while expression check, where i check something against unsigned values of the array, what is really checked is that something agains unsigned values of some weird numbers.
i tested it, with simple cout output:
IF i do unsigned(k[anyindexofk]) and the value contained in that spot is a positive number, i get the positive number of course which is unsigned
IF that number is negative though, the value won't be simply unsigned, but look very different, like i stepped over the array or something...i get this number "4294967292" when im instead expecting -2 to return as 2 or -4 to be 4.
(that number is for -4, -2 gives 4294967294)
I edited the sources with my new stuff, thanks for the help!
EDIT 2: nvm i resolved with std::abs() using cmath libs of c++
would there have been any other ways without using abs?
In your code, you have:
while (s[i]>=0)
{
k[j]+=s[i]; ++i;
}
Where s is initialized like so
int s[n+1]={3,-2,4,-4,6};
This is one obvious bug. Your while loop will overstep the array and hit garbage data that may or may not be zeroed out. Nothing stops i from being bigger than n+1. Clean up your code so that you don't overstep arrays, and then try debugging it. Also, your question is needs to be much more specific for me to feel comfortable answering your question, but fixing bugs like the one I pointed out should make it easier to stop running into inconsistent, undefined behavior and start focusing on your algorithm. I would love to answer the question but I just can't parse what you're specifically asking or what's going wrong.
I'm new in C++, I have a small project,
I should get 10 numbers from user and then show in result.
so I wrote this code :
#include<stdio.h>
int main() {
int counter=1,
allNumbers;
float score;
while(counter <= 10) {
scanf("%f",&score);
counter++;
}
printf("Your entered numbers are : %s\n",allNumber);
}
for example user enter 2 3 80 50 ... and I want show 2,3,80,50,... in result.
But I don't know what should I do !
I do not know what book you are using, but the authors appear to teach you C before going into the C++ land. Without discussing their motives, I'll write an answer to be similar to your style of code before discussing an ideal C++ solution.
You need an array to store your numbers: double score[10]
Array are indexed starting from zero, so change counter to start at zero and go to nine (instead of starting at one and going to ten, like you have now)
Since score is an array, use &score[count] in the call of scanf
To print ten numbers you need a loop as well. You need a flag that tells you whether or not you need a comma after the number that you print. Add a printf("\n") after the loop.
As far as an "ideal" C++ solution goes, it should look close to this one:
istream_iterator<double> eos;
istream_iterator<double> iit(cin);
vector<double> score;
copy(iit, eos, back_inserter(score));
ostream_iterator<double> oit (cout, ", ");
copy(score.begin(), score.end(), oit);
However, discussing it would remain hard until you study the C++ standard library and its use of iterators.
You can do it by declaring an array of ten numbers.
your code goes here:
#include <stdio.h>
int main() {
int counter=0;
float allNumbers[10];
while(counter < 10) {
scanf("%f",&allNumbers[counter]);
counter++;
}
printf("Your entered numbers are : \n");
counter=0;
while(counter < 10) {
printf("%f , ",allNumbers[counter]);
counter++;
}
}