#include <bits/stdc++.h>
using namespace std;
int gcd(long long int a, long long int b){
if(a||b==0){
return 0;
}
else if(b==a){
return a;
}
else if(a>b){
return gcd(a-b,b);
}
else{
return gcd(a,b-a);
}
}
int lcm(long long int a,long long int b){
return a*b/(gcd(a,b));
}
int main(){
long long int answer=1;
for (int i = 2; i<=20; i++) {
answer=lcm(i,answer);
cout<<answer;
}
cout<<answer;
return 0;
}
i wrote this code for problem 5 in project euler. however the output screen is showing nothing and is getting hanged. i put a few debugging cout statements and i understood that in the main function the it is entering the loop but it is not continuing the excution after the call for lcm.
the program is to find the lcm of numbers from 1 to 20. i used the formula llcm= a*b/gcd(a,b). where in gcd also i used the recursive euclidian algorithm. i am not able to trace out the reason for this bug . could anyone help pls.
also if there any suggestions regarding my coding style (indentation, type casting, variable names, algorithm or anything) please point it out. i am beginner so i do not know much regarding c++ and programming styles.
Your program is becoming stuck because of this line:
if (a || b == 0) {
The == operator has higher precedence than ||, so the condition is in fact the same as:
if (a || (b == 0)) {
Which in C(++) is the same as:
if ((a != 0) || (b == 0)) {
That is, if a is non-zero OR b is zero. a will be non-zero straight away, hence your program will always try to divide by zero, which causes problems. I am not sure where you found this version of the algorithm, a cursory search results in a much simpler variant:
int gcd(int a, int b) {
if (b == 0) {
return a;
} else {
return gcd(b, (a % b));
}
}
As for the second part of your question, there are many little (stylistic) issues in your code that I would change. Inconsistent spacing, unnecessary use of long long int (an int would do just fine here) … But for these, I recommend the codereview StackExchange.
Related
The question asks me to find the greatest power devisor of (number, d) I found that the function will be like that:
number % d^x ==0
I've done so far using for loop:
int gratestDevisor(int num, int d){
int p = 0;
for(int i=0; i<=num; i++){
//num % d^i ==0
if( (num % (int)pow(d,i))==0 )
p=i;
}
return p;
}
I've tried so much converting my code to recursion, I can't imagine how to do it and I'm totally confused with recursion. could you give me a tip please, I'm not asking you to solve it for me, just some tip on how to convert it to recursion would be fine.
Here is a simple method with recursion. If ddivides num, you simply have to add 1 to the count, and divide num by d.
#include <stdio.h>
int greatestDevisor(int num, int d){
if (num%d) return 0;
return 1 + greatestDevisor (num/d, d);
}
int main() {
int num = 48;
int d = 2;
int ans = greatestDevisor (num, d);
printf ("%d\n", ans);
return 0;
}
A recursive function consist of one (or more) base case(es) and one (or more) calls to the function itself. The key insight is that each recursive call reduces the problem to something smaller till the base case(es) are reached. State (like partial solutions) are either carried in arguments and return value.
You asked for a hint so I am explicitly not providing a solution. Others have.
Recursive version (which sucks):
int powerDividing(int x, int y)
{
if (x % y) return 0;
return 1 + powerDividing(x/y, y);
}
I am trying to find a faster lcm function than I currently have. I tried to look up some better gcd but couldn't find anything that solves the problem.
#include <bits/stdc++.h>
const int MOD = 1000000007;
using namespace std;
long gcd (long a, long b)
{
if (a == 0) return b;
return gcd (b % a, a);
}
long lcm (long a, long b)
{
if (a == 0 || b == 0) return 0;
return a * b / gcd (a, b);
}
The mothed you showed is probably the fastest one, but if you want to avoid recursion, try this, it may be slightly faster.
long gcd (long a, long b)
{
while (a != 0)
{
b %= a;
if (b == 0)
return a;
a %= b;
}
return b;
}
Though this gcd algorithm is not that bad (and the number of iterations is always small), you can try the Stein's variant, which trades divisions for much faster shifts.
https://en.wikipedia.org/wiki/Binary_GCD_algorithm
Anyway, this does not improve the asymptotic complexity.
I made a program for codechef and its wrong apparantly (although all tests have been positive). The code is:
#include <iostream>
using namespace std;
int g (int a,int b){
return b == 0 ? a : g(b, a % b);
}
int l (int a, int b){
return (a*b)/(g(a,b));
}
int main() {
int n;
cin >> n;
int a[n],b[n];
for (int x = 0;x<n;x++){
cin >> a[x] >> b[x];
}
for (int x = 0;x<n;x++){
cout << g(a[x],b[x]) << " "<< l(a[x],b[x]) << endl;
}
return 0;
}
Codechef won't tell me what integers dont work, and im pretty sure my gcd function is legit.
Since gcd is properly defined as the largest non-negative common divisor, you can save yourself the annoying details of signed division, e.g.,
static unsigned gcd (unsigned a, unsigned b)
{
/* additional iteration if (a < b) : */
for (unsigned t = 0; (t = b) != 0; a = t)
b = a % b;
return a;
}
Likewise for lcm; but the problem here is that (a*b) may overflow. So if you have two large (signed) int values that are co-prime, say: 2147483647 and 2147483629, then gcd(a,b) == 1, and (a*b)/g overflows.
A reasonable assumption on most platforms is that unsigned long long is twice the width of unsigned - although strictly speaking, it doesn't have to be. This is also a good reason to use exact types like [u]int32_t and [u]int64_t.
One thing you can be sure of is that a/g or b/g will not cause any issues. So a possible implementation might be:
static unsigned long long lcm (unsigned a, unsigned b)
{
return ((unsigned long long) a) * (b / gcd(a, b)));
}
If your test values are 'positive' (which is what I think you mean), you can cast them prior to (unsigned) prior to call. Better yet - replace all your int variables with unsigned int (though the loop variables are fine), and save yourself the trouble to begin with.
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 7 years ago.
Improve this question
I write my program calculation:
#include <stdio.h>
int cal(int a, int b){
if (a == 0){
return 1;
}
else if (a == 1){
return b;
}
else{
int c = a / b;
return (cal(a, c) + 1);
}
}
int main(){
printf("Enter values: ");
int a, b;
scanf("%d%d", &a, &b);
printf("%d\n", cal(a, b));
return 0;
}
But when I runing my program. I have an error.
So. my program wrong or what problem with programming C, C++?
Thanks for view my question.
I'm fine! Thanks for everyone. This is my fail.
I change my program same:
#include <stdio.h>
int cal(int a, int b){
if (a == 0){
return 0;
}
else if (a == 1){
return b;
}
else if (b == 0){
return 1;
}
else if (b == 1){
return 0;
}
else{
return (cal(a, b/a) + 1);
}
}
int main(){
printf("Enter values: ");
int a, b;
scanf("%d%d", &a, &b);
printf("%d\n", cal(a, b));
return 0;
}
int c = a / b;
Will give you a runtime error if you do not check that b is not allowed to be 0.
Add a condition to verify that b is in fact not 0 and if it is, do not perform the division operation.
You run into an infinite recursion. It looks as if you had a termination condition, but the exits without recursion check on a, which will always be the same in your calls.
As is, your algorithm calls cal(a, b) and cal(a, a / b) respectively in odd and even recursion steps. Eventually, you run out of stack.
Revise your algorithm so that deeper recursions progress towards a base state, whcih you should check.
If you want to calculate the logarithm of a to the base b, you should keep the base b constant across calls and sucessively divide a by the base until you reach the case where the value a falls below the base:
int intlog(int a, int b)
{
if (a < b) return 0;
return cal(a / b, b) + 1;
}
I'm writing a mixed numeral class and need a quick and easy 'greatest common divisor' function. Can anyone give me the code or a link to the code?
The libstdc++ algorithm library has a hidden gcd function (I'm using g++ 4.6.3).
#include <iostream>
#include <algorithm>
int main()
{
std::cout << std::__gcd(100,24); // print 4
return 0;
}
You are welcome :)
UPDATE: As #chema989 noted it, in C++17 there is std::gcd() function available with <numeric> header.
I'm tempted to vote to close -- it seems difficult to believe that an implementation would be hard to find, but who knows for sure.
template <typename Number>
Number GCD(Number u, Number v) {
while (v != 0) {
Number r = u % v;
u = v;
v = r;
}
return u;
}
In C++ 17 or newer, you can just #include <numeric>, and use std::gcd (and if you care about the gcd, chances are pretty fair that you'll be interested in the std::lcm that was added as well).
A quick recursive version:
unsigned int gcd (unsigned int n1, unsigned int n2) {
return (n2 == 0) ? n1 : gcd (n2, n1 % n2);
}
or the equivalent iterative version if you're violently opposed to recursion (a):
unsigned int gcd (unsigned int n1, unsigned int n2) {
unsigned int tmp;
while (n2 != 0) {
tmp = n1;
n1 = n2;
n2 = tmp % n2;
}
return n1;
}
Just substitute in your own data type, zero comparison, assignment and modulus method (if you're using some non-basic type like a bignum class, for example).
This function actually came from an earlier answer of mine for working out integral aspect ratios for screen sizes but the original source was the Euclidean algorithm I learnt a long time ago, detailed here on Wikipedia if you want to know the math behind it.
(a) The problem with some recursive solutions is that they approach the answer so slowly you tend to run out of stack space before you get there, such as with the very badly thought out (pseudo-code):
def sum (a:unsigned, b:unsigned):
if b == 0: return a
return sum (a + 1, b - 1)
You'll find that very expensive on something like sum (1, 1000000000) as you (try to) use up a billion or so stack frames. The ideal use case for recursion is something like a binary search where you reduce the solution space by half for each iteration. The greatest common divisor is also one where the solution space reduces rapidly so fears about massive stack use are unfounded there.
For C++17 you can use std::gcd defined in header <numeric>:
auto res = std::gcd(10, 20);
The Euclidean algorithm is quite easy to write in C.
int gcd(int a, int b) {
while (b != 0) {
int t = b;
b = a % b;
a = t;
}
return a;
}