highest cf between 2 numbers c++ - c++

This is a program to find highest common factor:
#include <iostream>
enter code here using namespace std;
void main ()
{
int max=0 , min=0 , x,y,hcf=0;
cout<<"enter 2 numbers\n";
cin>>x>>y;
if (x>y)
{
max=x;
min=y;
}
else if (y>x)
{
max=y;
min=x;
}
if
(max%min==0)
{ hcf=min;
cout<<"highest cf is:"<<hcf<<endl;}
else
{
hcf=min;
do
{
hcf--;
}
while (max%hcf!=0 && min%hcf!=0);
cout<<"highest cf is:"<<hcf<<endl;
}
system ("pause");
}
although when i test it ; it takes the condition max% hcf !=0 and ignores the second one ... for example if i input 12 and 8 then 12 is called max and 8 is min then it outputs 6 as hcf
that means it ignored the second condition ... as i understand of course.
so where is my mistake ?

A easy solution to get the HCF is to do this.
int HCF(int num1, int num2)
{
for(int i = num1; i > 2; i++)
{
if(num1 % i == 0 && num2 % i == 0) return i;
}
return 1;
}

Related

C++ Gapful Numbers Crashing

I was doing this program in which I am supossed to print gapful numbers all the way up to a specific value. The operations are correct, however, for some reason after printing a couple of values the program crashes, what can I do to fix this problem?
Here's my code:
#include<math.h>
#include<stdlib.h>
using namespace std;
void gapful(int);
bool gapCheck(int);
int main(){
int n;
cout<<"Enter a top number: ";
cin>>n;
gapful(n);
system("pause");
return 0;
}
void gapful(int og){
for(int i=0; i<=og; i++){
fflush(stdin);
if(gapCheck(i)){
cout<<i<<" ";
}
}
}
bool gapCheck(int n){
int digits=0;
int n_save,n1,n2,n3;
if(n<100){
return false;
}
else{
n_save=n;
while(n>10){
n/=10;
digits++;
}
digits++;
n=n_save;
n1=n/pow(10, digits);
n2=n%10;
n3=n1*10 + n2;
if(n%n3 == 0){
return true;
}
else{
return false;
}
}
}
I'm open to any suggestions and comments, thank you. :)
For n == 110, you compute digits == 3. Then n1 == 110 / 1000 == 0, n2 == 110 % 10 == 0, n3 == 0*10 + 0 == 0, and finally n%n3 exhibits undefined behavior by way of division by zero.
You would benefit from more functions. Breaking things down into minimal blocks of code which represent a single purpose makes debugging code much easier. You need to ask yourself, what is a gapful number. It is a number that is evenly divisible by its first and last digit. So, what do we need to solve this?
We need to know how many digits a number has.
We need to know the first digit and the last digit of the number.
So start out by creating a function to resolve those problems. Then, you would have an easier time figuring out the final solution.
#include<math.h>
#include <iostream>
using namespace std;
void gapful(int);
bool gapCheck(int);
int getDigits(int);
int digitAt(int,int);
int main(){
int n;
cout<<"Enter a top number: " << endl;
cin>>n;
gapful(n);
return 0;
}
void gapful(int og){
for(int i=1; i<=og; ++i){
if(gapCheck(i)){
cout<<i << '-' <<endl;
}
}
}
int getDigits(int number) {
int digitCount = 0;
while (number >= 10) {
++digitCount;
number /= 10;
}
return ++digitCount;
}
int digitAt(int number,int digit) {
int numOfDigits = getDigits(number);
int curDigit = 0;
if (digit >=1 && digit <= numOfDigits) { //Verify digit is in range
while (numOfDigits != digit) { //Count back to the digit requested
number /=10;
numOfDigits -=1;
}
curDigit = number%10; //Get the current digit to be returned.
} else {
throw "Digit requested is out of range!";
}
return curDigit;
}
bool gapCheck(int n){
int digitsN = getDigits(n);
if (digitsN < 3) { //Return false if less than 3 digits. Single digits do not apply and doubles result in themselves.
return false;
}
int first = digitAt(n,1) * 10; //Get the first number in the 10s place
int second = digitAt(n,digitsN); //Get the second number
int total = first + second; //Add them
return n % total == 0; //Return whether it evenly divides
}

The Coursera autograder gives me Unknown Signal 11

I'm in a class in Algorithms and now we are taking Greedy Algorithms.
Two of my solutions output "Uknown Signal 11" on some of the test cases.
However, I drove my program to the limit with the largest inputs possible.
It works just fine on my PC. However on Coursera's grader, it throws tgghis cryptic message of Unknown Signal 11.
Will this go away if I change to Python for example?
Here's the first code exhibiting the problem:
#include <iostream>
#include <utility>
#include <algorithm>
using namespace std;
bool sortAlg(pair<double, pair<uint64_t,uint64_t>> item1, pair<double,
pair<uint64_t,uint64_t>> item2)
{
return (item1.first >= item2.first);
}
int main()
{
uint64_t n, index = 0;
double W, val;
cin >> n >> W;
pair<double, pair<uint64_t,uint64_t>> items[n];
for (int i=0; i <n; i++)
{
cin >> items[i].second.first >> items[i].second.second;
items[i].first = (double)items[i].second.first / (double)items[i].second.second;
}
sort(items,items+n, sortAlg);
while(W > 0 && n > 0)
{
if (items[index].second.second <= W)
{
val += items[index].second.first;
W -= items[index].second.second;
index++;
n--;
}
else
{
val += items[index].first * W;
W = 0;
index++;
n--;
}
}
printf("%.4f",val);
return 0;
}
I think this has to do with the while loop, but I can't think of anything where the program will make an out of bounds array call using index.
Anyways it is a fractional knapsack implementation.
Here's the second code which also gives unknown signal 11:
#include <iostream>
#include <string>
#include<vector>
#include <algorithm>
#include <utility>
using namespace std;
bool sortAlg(string num1, string num2)
{
if (num1[0] > num2[0]) return true;
else if (num1[0] < num2[0]) return false;
else
{
if (num1.size() == 1 && (num1[0] > num2[1])) return true;
else if (num1.size() == 1 && (num1[0] < num2[1])) return false;
else if (num2.size() == 1 && (num1[1] > num2[0])) return true;
else if (num2.size() == 1 && (num1[1] < num2[0])) return false;
else if (num1 == "1000" || num2 == "1000") return (num1 < num2);
else
{
if (num1.size() == num2.size()) return (num1 > num2);
else
{
return (num1[1] > num2[1]);
}
}
}
}
int main()
{
string num;
int n, n2 = 1;
cin >> n;
//int numbers[n];
vector<string> numbers2;
for (int i =0; i <n; i++)
{
num = to_string(n2);
cout << num << endl;
numbers2.push_back(num);
n2 += 10;
}
sort(numbers2.begin(), numbers2.end(), sortAlg);
for (auto number : numbers2)
{
cout << number;
}
return 0;
}
I suspect the sortAlg function used in sort function, but on my PC it is relatively fast. And the problem statement required some weird sorting.
The problem was given a set of numbers, arrange them to make thebiggest number possible.
If given 9, 98, 2, 23, 21 for example it should give me 99823221.
(9 > 98 > 23 > 2 > 21)
So I sort by the first digit then the next and so on.
You have a StackOverflow error.
The necessary stack size depends on the depth of your recursion, the number of parameters of your recursive function and on the number of local variables inside each recursive call.
In Python, you have to set the necessary stack size. The starter files provided in Python 3 would have the sample below:
import threading
sys.setrecursionlimit(10 ** 6) # max depth of recursion
threading.stack_size(2 ** 27) # new thread will get stack of such size
...
threading.Thread(target=main).start()
Note how the stack_size is allocated.
It's just an additional information related to Coursera grader.
In the week 6 the same course , if you declare a 2D array for the dynamic programming problem, the grader gives the Signal 11 error and program fails even if it is working perfectly fine on local machine .
Solution to above problem - replace 2-D array by 2D vector (in case of C++) and submit again. The grader will accept the code solution and no signal 11 error will be thrown.

Programming a boolean program using recursion

I have this homework to do and I dont really understand why my program doesnt really work(prints 1 constantly).
I am supposed create a program that receives a number and a digit from the user(we can assume that the input is ok)
and it prints 1 in case the digit appears inside the number even times. In case it appears odd amount of times it will print 0.
I have to use a boolean recursion function.
can someone please tell me whats wrong with it?
#include <iostream>
using namespace std;
bool isEven(int num, int dig);
void main()
{
bool res;
int num, dig;
cout << "Please enter a number and a digit" << endl;
cin >> num >> dig;
cout << isEven(num, dig);
}
bool isEven(int num, int dig)
{
bool res;
int counter = 0;
if (num < 10)
{
if (counter % 2 != 0)
res=false;
else
res=true;
return res;
}
else
{
res=isEven(num / 10, dig);
if (num % 10 == dig)
counter++;
return res;
}
}
You're not passing the value of your counter down through your recursive calls - it's effectively unused in your current implementation.
You're also missing one check if dig % 10 == num - in your code, you never check the last digit of the number.
bool isEven(int num, int dig, int counter)
{
bool res;
if (num % 10 == dig)
counter++;
if (num < 10)
{
if (counter % 2 != 0)
res=false;
else
res=true;
return res;
}
else
{
res=isEven(num / 10, dig, counter);
return res;
}
}
And you can just call it with isEven(num, dig, 0) or create a wrapper function that takes just num and dig and calls this version with 0.
Note that there's a (imo) more elegant recursive expression of this function without using counters, although it's got some slightly unintuitive bits to it:
bool isEven(int num, int dig)
{
// Base case, single digit
// If num % 10 == dig on this last digit, we've got 1 match (odd, so return false)
if (num < 10)
return num % 10 != dig;
bool result = isEven(num / 10, dig);
if (num % 10 == dig) // This digit matches, count one more/flip the result
result = !result;
return result;
}

How to check if a given number can be represented as the sum of 2 even numbers?

I want to read in a number and check if the number can be written as the sum of 2 even numbers.
Input: A line containing the number w.
Output:Print YES, if the number can be divided into two parts, each of them being even; and NO in the opposite case.
I've tried this code.
#include <stdio.h>
int main () {
int w,i,b;
i=w%b;
printf("enter the weight");
scanf("%d", &w);
for (b=2;b<=10;b=b+2) {
if (i==0 && i&2==0) {
printf("YES");
} else {
printf("NO");
}
}
return 0;
}
but it's not showing any correct output. Can you tell me what am I missing here?
#include<bits/stdc++.h>
using namespace std;
int main() {
int t;
cin>>t;
if(t==2)
cout<<"NO"<<endl;
else if(t%2==0)
cout<<"YES"<<endl;
else
cout<<"NO"<<endl;
return 0; }
The explanation here is:
No odd number can be divided into two even parts --> odd - even = odd
Almost every even number can be divided into two even parts --> even - even = even
Edge case is: 2; as it can NOT be divided into two even parts, 1 is odd number, and can not be divided into 2 & 0 as one boy will not take part in addition to that 0 is not even number
I created a shorter and most likely easier to comprehend code. Try this:
int main() {
int number;
cin >> number;
if (number % 2==0 && number != 2){
std::cout << "YES";
} else {
std::cout << "NO";
}
}
Continuing from the comment, w should be unsigned int as you cannot have a negative weight. Additionally, if the least significant bit is 1 the number is odd. Putting those together in a simple mellon splitting algorithm, you could do something like the following to determine if each can have an even weighted slice:
#include <stdio.h>
int main (int argc, char **argv) {
int i, j, wt = 0;
for (i = 1; i < argc && sscanf (argv[i], "%u", &wt) == 1; i++) {
int sliced = 0;
if (wt & 1) goto odd;
for (j = 0; j < wt/2; j++) {
if (!(((wt/2 - j) & 1) | ((wt/2 + j) & 1))) {
printf (" %3u - Yes (one gets %u, other %u)\n", wt,
wt/2 - j, wt/2 + j);
sliced = 1;
break;
}
}
odd:;
if (!sliced) printf (" %3u - No\n", wt);
}
return 0;
}
Example Use/Output
$ for i in {1..20}; do ./bin/evenmellons $i; done
1 - No
2 - No
3 - No
4 - Yes (one gets 2, other 2)
5 - No
6 - Yes (one gets 2, other 4)
7 - No
8 - Yes (one gets 4, other 4)
9 - No
10 - Yes (one gets 4, other 6)
11 - No
12 - Yes (one gets 6, other 6)
13 - No
14 - Yes (one gets 6, other 8)
15 - No
16 - Yes (one gets 8, other 8)
17 - No
18 - Yes (one gets 8, other 10)
19 - No
20 - Yes (one gets 10, other 10)
To compute and see all the possible even weighted slice combinations the friends can share, you can simply omit the break. You can make it selectable at the compile stage by wrapping the break in its own definition. For example:
#ifndef SHOWALL
break;
#endif
Compile as usual for normal behavior, compile with -DSHOWALL to compute and show all possible slice combinations.
#include<iostream>
#include<string>
using namespace std;
int main()
{
int weight;
cin>>weight;
string soln = weight>2 && weight % 2==0 ? "Yes" : "No";
cout<<soln;
}
Here, You just need to check it can divide or not and also the divided part must contain even number...
My current attempt is:
#include <stdio.h>
int main () {
int w,x,y;
printf("Enter The Weight");
scanf("%d" , &w) ;
for(y=2;y<=w;y=y+2) {
x=w-y;
if(x%2==0) {
for(x;x>=y;x=w-y) {
y=y+2 ;
printf("Yes,It can divide to %d", x);
printf("and %d\n", y-2);
}
} else {
printf("No");
}
}
return 0;
}
Here is my answer in Python 3 (Answer accepted by Codeforces)
w = int(input())
if w%2==0 and w!=2:
print("YES")
else:
print("NO")
If the melon can be divided into two even numbers 2x and 2y (x, y ≥ 1), then the sum is 2*(x+y).
Thus any even number ≥ 4 can be divided into two even parts.
To check for an even number, you can simply use x%2 == 0.
any even number can be divided into two evens. Except 2, 2=1+1. Hence the condition.
#include <bits/stdc++.h>
using namespace std;
int main() {
int w;
cin>>w;
if(w>2 && w%2==0){
cout<<"YES"<<endl;
}
else{
cout<<"NO"<<endl;
}
return 0;
}
try this one.
#include<stdio.h>
int main(){
int a,b,c;
scanf("%d",&a);
if(a<100 && a>=1){
if(a%2==0 && a>3){
b=a/2;
if(b%2==0){
printf("YES\n");
printf("%d %d",b,b);
}else{
b=b+1;
c=b-2;
printf("YES\n");
printf("%d %d",c,b);
}
}else{
printf("NO");
} else{
printf("Invalid Input");
}
return 0;
}
#include <iostream>
using namespace std;
int main() {
int w;
cin>>w;
if (w>2 && w%2==0) {
cout<<"YES";
} else {
cout<<"NO";
}
return 0;
}

How to average positive inputs until a negative input is given

How can I accept and average positive numbers? When a negative number is entered, it should terminate the loop and display the average (excluding the negative number).
#include <iostream>
using namespace std ;
int main () {
int x,counter=0,sum;
float avg;
while (x>0) {
if(x<0) {
sum+=x;
counter++;
continue;
} else if (x>0) {
cin>>x;
sum+=x;
counter ++;
}
}
avg=(float)sum/counter;
cout<<avg<<endl;
return 0 ;
}
#include <iostream>
using namespace std;
int main() {
int sum = 0, count = 0, input; // initialize all variables
while (true) { // loop forever (until break is reached below)
cin >> input; // get user input
if (input < 0) break; // if it's negative, exit loop
sum += input; // otherwise add it to the running sum
count++; // increase the count by 1
}
if (count > 0) cout << (double)sum / count; // if we have at least one number, display avg
else cout << "No numbers to average" << endl; // else complain.
return 0;
}
Note that this will fail if the user provides bad input. If you need it to handle bad input, see here about cin types.
The implementation that you have immediately adds the input to your sum.
int main () {
int x,counter=0,sum;
float avg;
while (x>0) {
cin >> x;
if (x>0) {
sum+=x;
counter ++;
}
}
avg=(float)sum/counter;
cout<<avg<<endl;
return 0 ;
}
This would allow you to check the input before adding to your total.
It is also important to mention to avoid dividing by zero if the user's first input is a negative number.
here is an improved version, that checks if loop exist without any positive integers entered to avoid divide by zero error
#include <iostream>
using namespace std ;
int main () {
int x;
float counter=0,sum;
float avg;
bool isPositive = true;
while ( isPositive) {
cin>>x;
if(x>0)
{
sum+=x;
counter ++;
}
else {
isPositive = false;
}
}
// if we divide by zero, an error will occur
if(counter > 0)
{
avg=(float)(sum/counter);
cout<<avg<<endl;
}
else cout << "Please enter positive numbers";
return 0 ;
}