So I wanted to write a function to calculate the Gcd or HCF of two numbers using the Divison method.This is my code:
#include <stdio.h>
#include <stdlib.h>
void gcd(int x, int y)
{
int g,l;
if (x >= y)
{
g = x;
l = y;
}
else
{
g = y;
l = x;
}
while (g % l != 0)
{
g = l;
l = g % l;
}
printf("The GCD of %d and %d is %d", x, y, l);
}
int main(void)
{
gcd(8, 3);
return 0;
}
I am getting no output with this(error?): Process returned -1073741676 (0xC0000094)
Is there a problem with my loop?
In:
g = l;
l = g % l;
the assignment g = l loses the value of g before g % l is calculated. Change it to:
int t = g % l;
g = l;
l = t;
I use this loop while to find the gcd of two numbers like this:
void gcd(int x, int y)
{
int k=x,l=y;
if(x>0&&y>0)
{
while(x!=0&&y!=0)
{
if(x>y)
{
x=x-y;
}
else
{
y=y-x;
}
}
}
printf("\nThe GCD of %d and %d is %d", k, l, x);
}
int main(void)
{
gcd(758,306);
return 0;
}
Examples:
Input:
x=758 , y=306
x=27 , y=45
x=3 , y=8
Output:
printf("\nThe GCD of 758 and 306 is 2");
printf("\nThe GCD of 27 and 45 is 9");
printf("\nThe GCD of 3 and 8 is 1");
First of all, take into account that you are exchanging the numbers when x >= y which means that you try to put in x the smaller of the two. For GDC, there's no need to do
this, as the remainder of a division by a bigger number is always the original number, so if you have the sequence 3, 8, the first remainder will be 3, and the numbers switch positions automatically as part of the algorithm. So there's no need to operate with g (I guess for greater) and l (for lesser) so you can avoid that.
#include <stdio.h>
#include <stdlib.h>
void gcd(int x, int y)
{
int g,l;
if (x >= y)
{
g = x;
l = y;
}
else
{
g = y;
l = x;
}
Then, in this second part (the loop part) you have to take into account that you are calculating g % l twice in the same loop run (this is not the Euclides' algorithm).
while (g % l != 0)
{
g = l;
l = g % l;
}
You should better use a new variable r (for remainder, but I should recommend you to use longer, descriptive names) so you have always an idea of what the variable holds.
int r;
while ((r = g % l) != 0) {
g = l;
l = r;
}
you see? I just do one division per loop, but you make a l = g % l; which modifies the value of l, making you go through two iterations of the loop in one.
The final program is:
#include <stdio.h>
#include <stdlib.h>
int gcd(int greater, int lower)
{
int remainder;
while ((remainder = greater % lower) != 0) {
printf("g=%d, l=%d, r=%d\n", greater, lower, remainder);
greater = lower;
lower = remainder;
}
return lower; /* remember that remainder got 0 in the last loop */
}
int main(void)
{
int x = 6, y = 8;
printf("The GCD of %d and %d is %d\n",
x, y, gcd(x, y));
printf("The GCD of %d and %d is %d\n",
y, x, gcd(y, x));
return EXIT_SUCCESS;
}
(I have added a trace printf in the gcd() loop to show how the variables are changing, and both calculations ---changing the parameter values--- to show what I said above about the automatic change in order. Also, it's better to use the gcd() as a function that returns the value, and let main() decide if it wants to print results, or use the value for something else.
Enjoy it!! :)
Related
As I see it the numerical sequence consists of 2 separate sequences. This is the code that I have so far. I am not sure if you must use a while or a for loop. I am fairly new at coding so if someone please could help me.
if the entered value is 10 it must give the first 10 terms of the sequence, and if I enter 5 it must give me the first 5 terms of the sequence.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main() {
int a, n = 1, t, y = 1; // First Numerical Sequence
int b, m = 2, s, x = 2; // Second Numerical Sequence
int d, r, z; // Extra
printf("Enter A Tn : ");
scanf(" %d", &z);
printf("\n");
while (n <= z) {
a = 15;
r = pow(2, n - y);
d = (9 * (r - 1)) / (2 - 1);
t = a + d;
printf("%d\n", t);
n += 2;
y++;
}
while (m <= z) {
b = 12;
r = pow(2, m - x);
d = (9 * (r - 1)) / (2 - 1);
s = b + d;
printf("%d\n", s);
m += 2;
x++;
}
printf("\n");
return 0;
}
This will get the job done.
#include <stdio.h>
int main(){
int val,ic; //iteration count, will print ic*2 number
scanf("%d %d",&val,&ic);
for(int i = 0;i<ic;i++){
printf("%d ",val);
val-=3;
printf("%d ",val);
val*=2;
}
printf("\n");
}
How to compile & run:
C:\Users\stike\Desktop>rem assume you saved it in a.c
C:\Users\stike\Desktop>gcc -o a a.c
C:\Users\stike\Desktop>a
15
5
15 12 24 21 42 39 78 75 150 147
If you want to print the same sequence starting from 15 and o till a certain number which the user inputs, you can follow the following code.
Hope you understood the sequence pattern when a number is given it is printed and reduce the number by 3, then it is printed and then twice the number and printed, and again reduce by 3, likewise, it flows on.
#include <stdio.h>
int main() {
int endNum;
int beginNum = 15;
printf("Enter the end: ");//(lineA) here we initialize the variables with beginNum as 15
scanf("%d", &endNum); //(Line B) let the user to input endNum of the sequence,in the example it is 147
while ((beginNum-3) <= endNum) { // checks the condition
printf("%d ", beginNum);
if(beginNum==endNum) return 0; //check whether you print the end number.
beginNum -= 3; // reduce by 3
printf("%d ", beginNum);
beginNum *= 2; // multiply by 2
}
return 0;
}
if you don't need to user input a endNum just initialize the value 147 to variable endNum.
And delete the lines A and B.
Here's another approach using static variables
#include <stdio.h>
int next(void) {
static int last, n = 0;
if (n++ == 0) return last = 15; // 1st element of sequence
if (n % 2) return last = last * 2; // odd elements
return last = last - 3; // even elements
}
int main(void) {
for (int k = 0; k < 10; k++) {
printf("%d ", next());
}
puts("");
return 0;
}
Mind the set of positive integers from 0 til L exclusive. For any positive integer n up to log2(K), can split the set in 2^n consecutive subsets of equal length. For example, for L = 256, n = 3, we'd get 2^3, or 8, subsets: {0..31}, {32..63}, {64..95}, {96..127}, {128..160}, {160..191}, {192..223}, {224..255}.
Let f(L,n,i) : Nat -> Nat -> Nat -> (Nat,Nat) return, given an arbitrary L and n, the subset that some i is contained in. For example, for f(256,3,100) = (96,127), because, if we divide the 0..255 range in 2^3 subsets, then number 100 is contained in the subset ranging from 96 to 127.
My question is, what is a fast implementation of f? I wonder if it is possible to do so in constant time, with just a few bitwise operations.
This works:
#include <stdio.h>
typedef struct { int a, b; } pair;
pair f(int L, int n, int i) {
int len = L / (1 << n);
int a = i / len * len;
return (pair) { a, a + len - 1 };
}
int main() {
pair p = f(256, 3, 100);
printf("%d %d\n", p.a, p.b);
}
I am not good with floating point, but looping works as expected:
#include <stdio.h>
#include <math.h>
typedef struct { double a, b; } paird;
paird fd(double L, double n, double i) {
double len = L / pow(2, n);
double a = 0, b;
while (b = a + len, b < i) {
a = b;
}
return (paird){ a, b };
}
int main() {
paird p = fd(127, 7, 100);
printf("%f %f\n", p.a, p.b); // (99.218750, 100.210938)
}
Quite obviously, just compute the length of each subset (l), divide i by l, and take the floor k. The desired range goes from l*k to l*(k+1)-1. In JavaScript:
function subrange_of_i(L, n, i) {
var l = L / (2 ** n); // or just `L >>> n`
var k = Math.floor(i / l);
return [l*k, l*(k+1)-1];
};
(TODO: convert to C for the sake of this answer.)
I have to write a program that will find a square root using the while loop. I was given this new_guess = (old_guess + (n / old_guess)) / 2.0; but I dont fully understand what to do with it, this is what I have:
int main(void)
{
double n, x, new_guess, old_guess, value;
printf("Enter a number:");
scanf("%lf", &n);
x = 1.00000;
while (new_guess >= n) {
new_guess = (old_guess + (n / old_guess)) / 2.0;
printf("%10.5lf\n", fabs(new_guess));
}
return 0;
}
x is the initial guess. Im really lost on how to do it. This is C also. I know its really wrong but I really dont understand how to make it start because when I enter a number it just stop right away.
Your program has undefined behavior because both new_guess and old_guess are uninitialized when you enter the loop.
The condition is also incorrect: you should stop when new_guess == old_guess or after a reasonable maximum number of iterations.
Here is a modified version:
#include <math.h>
#include <stdio.h>
int main(void) {
double n, x;
int i;
printf("Enter numbers:");
while (scanf("%lf", &n) == 1 && n >= 0.0) {
x = 1.0;
/* Using a while loop as per the assignment...
* a for loop would be much less error prone.
*/
i = 0;
while (i < 1024) {
double new_guess = (x + (n / x)) / 2.0;
if (new_guess == x)
break;
x = new_guess;
i++;
}
printf("%g: %.17g, %d iterations, diff=%.17g\n",
n, x, i, sqrt(n) - x);
}
return 0;
}
Given the start value, the number of iterations grows with the size of n, exceeding 500 for very large numbers, but usually less than 10 for small numbers. Note also that this algorithm fails for n = 0.0.
Here is a slightly more elaborate method, using the floating point break up and combine functions double frexp(double value, int *exp); and double ldexp(double x, int exp);. These functions do not perform any calculation but allow for a much better starting point, achieving completion in 4 or 5 iterations for most values:
#include <math.h>
#include <stdio.h>
int main(void) {
double n, x;
int i, exp;
printf("Enter a number:");
while (scanf("%lf", &n) == 1 && n >= 0.0) {
if (n == 0) {
x = 0.0;
i = 0;
} else {
frexp(n, &exp);
x = ldexp(1.0, exp / 2);
for (i = 0; i < 1024; i++) {
double new_guess = (x + (n / x)) / 2.0;
if (new_guess == x)
break;
x = new_guess;
}
}
printf("%g: %.17g, %d iterations, diff=%.17g\n",
n, x, i, sqrt(n) - x);
}
return 0;
}
Not really sure what the problem is here. I know I have the factorial function correct because I tested it separately. But the function that calculates e is tripping me up. All I have to do is add all the values after each factorial has been calculated. But I am having trouble translating that into C code. The problem for sure is in my second function. Any help or pointers would be appreciated.
#include <stdio.h>
#include <math.h>
#define NOERROR 0
#define DECIMAL_PLACES 16
#define EXPECTED_E 2.7182818284590452L
long calcFactorial(int);
double calcE(int);
long calcFactorial(int n)
{
long sum = 0;
sum = n;
if(n == 0)
{
return 1;
}
else
{
while(n != 1)
{
sum = sum * (n - 1);
n = n - 1;
}
printf("factorial sum: %ld\n", sum);
return sum;
}
}
double calcE(int n)
{
double e = 0;
int counter = 0;
for (counter = 0; counter < DECIMAL_PLACES; counter++)
{
e = e + (1/calcFactorial(n));
n--;
}
printf("Expected e value: %0.16Lf\n", EXPECTED_E);
printf("Calculated e value: %0.16d\n", e);
return e;
}
int main()
{
calcE(10);
}
You have a lot of errors in your code:
using long to store floating point result. Use double
passing n but looping using a bigger value: n becomes negative after a while: infinite loop
e = e + (1/calcFactorial(counter)); adds 0 to e most of the time because calcFactorial returns an integer (long)
EXPECTED_E constant had L suffix, which means long. Not what you want.
Fixed version:
#include <stdio.h>
#include <math.h>
#define NOERROR 0
#define DECIMAL_PLACES 16
#define EXPECTED_E 2.7182818284590452
long calcFactorial(int);
void calcE(int);
long calcFactorial(int n)
{
long sum = 0;
sum = n;
if(n == 0)
{
return 1;
}
else
{
while(n != 1)
{
sum *= (n - 1);
n = n - 1;
}
return sum;
}
}
void calcE(int n)
{
double e = 0;
int counter = 0;
for (counter = 0; counter < n; counter++)
{
e = e + (1.0/calcFactorial(counter));
}
printf("Expected e value: %0.16lf\n", EXPECTED_E);
printf("Calculated e value: %0.16lf\n", e);
}
int main( )
{
calcE(10);
}
This code outputs:
Expected e value: 2.7182818284590451
Calculated e value: 2.7182815255731922
Note: you are limited to a given maximum for n because after that you'll overflow long. Maybe consider using long long or unsigned long long for the factorial part (and even with that you're severely limited).
Jean-François Fabre highlighted your formal errors quite well, but it is not so far fetched to calculate with integers up to the final division--which must be done with floats, of course. The trick can be done with a method called binary splitting and, to my own surprise, it works very well native doubles, only one decimal digit off. It is also very simple to implement (code below written with legibility in mind).
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#define BS_AFU 0
#define BS_AOK 1
static int exp1_bin_split(uint64_t a, uint64_t b, uint64_t *P, uint64_t *Q){
int err = BS_AOK;
uint64_t p1, q1, p2, q2, t1, one;
one = 1UL;
t1 = b - a;
if(t1 == one){
*P = one;
*Q = b;
return err;
}
t1 = (a + b) >> 1;
err = exp1_bin_split(a, t1, &p1, &q1);
if(err != BS_AOK){
return err;
}
err = exp1_bin_split(t1, b, &p2, &q2);
if(err != BS_AOK){
return err;
}
*P = q2 * p1 + p2;
*Q = q1 * q2;
return err;
}
#include <float.h>
static int exp1(double *a){
int err = BS_AOK;
uint64_t p = 0UL, q = 0UL, zero = 0UL;
double dp, dq;
// DBL_DIG + 2 = 17 here on my machine
// had DBL_DIG + 1 first but found out via T&E that
// one more is still inside the precision of a binary64
err = exp1_bin_split(zero, DBL_DIG + 2, &p, &q);
if(err != BS_AOK){
return err;
}
p = p + q;
dp = (double) p;
dq = (double) q;
*a = dp/dq;
return err;
}
int main(void){
double e = 0.0;
int err = BS_AOK;
err = exp1(&e);
if(err != BS_AOK){
fprintf(stderr,"Something went wrong in computing e\n");
exit(EXIT_FAILURE);
}
printf("exp(1) ~ 2.7182818284590452353602874713526624978\nexp1 ~ %.20g\n",e);
exit(EXIT_SUCCESS);
}
It uses the same algorithm as you do but does not compute the individual fractions and sums them up as floats but does it all at once with integers such that we have a large fraction at the end to resemble the approximation of exp(1). That explanation is a bit over-simplified, please read the linked paper for the details.
I am getting wrong result for my LCM program.
Ifirst find gcd of the numbers and then divide the product with gcd.
int gcd(int x, int y)
{
while(y != 0)
{
int save = y;
y = x % y;
x = save;
}
return y;
}
int lcm(int x, int y)
{
int prod = x * y;
int Gcd = gcd(x,y);
int lcm = prod / Gcd;
return lcm;
}
Any help much appreciated.
Your gcd function will always return 0. Change
return y;
to
return x;
Understand the Euclid's algorithm:
RULE 1: gcd(x,0) = x
RULE 2: gcd(x,y) = gcd(y,x % y)
consider x = 12 and y = 18
gcd (12, 18)
= gcd (18, 12) Using rule 2
= gcd (12,6) Using rule 2
= gcd (6, 0) Using rule 1
= 6
As you can see when y becomes zero x will be the gcd so you need to return x and not y.
Also while calculating lcm you are multiplying the numbers first which can cause overflow. Instead you can do:
lcm = x * (y / gcd(x,y))
but if lcm cannot fit in an int you'll have to make it long long
Problem 1) int gcd = gcd(x,y);
gcd is already defined to be a function. You cannot define a variable with the same name.
Problem 2) Change return y to return x in gcd() otherwise 0 will be returned everytime.
Problem 3) x * y may overflow if x and y are large.
You should return x instead of y in your gcd function.
Also, are you sure the product x*y will always fit into an int? Might be a good idea to use a long long for that as well.
#include <iostream>
using namespace std;
long long gcd(long long int a, long long int b){
if(b==0)
return a;
return gcd(b,a%b);
}
long long lcm(long long a,long long b){
if(a>b)
return (a/gcd(a,b))*b;
else
return (b/gcd(a,b))*a;
}
int main(){
long long int a ,b ;
cin>>a>>b;
cout<<lcm(a,b)<<endl;
return 0;
}
This C program is different approach towards finding LCM
#include<stdio.h>
int main()
{
int a,b,lcm=1,i=2;
printf("Enter two numbers to find LCM\n" );
scanf("%d %d",&a ,&b);
while(i <= a*b)
{
if(a%i==0 & b%i==0)
{
lcm=lcm*i;
a=a/i;
b=b/i;
i=i-1;
}
if( a%i==0 & b%i!=0)
{
lcm=lcm*i;
a=a/i;
i=i-1;
}
if( b%i==0 & a%i!=0)
{
lcm=lcm*i;
b=b/i;
i=i-1;
}
i++;
}
printf("The LCM of numbers is %d\n", lcm);
}