find lowest common multiple - c

Here I am trying to find lowest common multiple of an array of numbers. I used the following formula to find the value which uses greatest common divisor to find out LCM.
My program calculates GCD correctly, but when it comes to find out LCM using GCD it gives wrong LCM value. What might be wrong in my logic. Any help would be much appreciated.
#include <stdio.h>
int main() {
int arr[10] = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 };
int GCD = findGCD(arr[0], arr[1]);
int LCM = (arr[0] * arr[1]) / GCD;
int i;
for (i = 2; i < sizeof(arr) / sizeof(arr[0]); i++) {
int temp = GCD;
GCD = findGCD(temp, arr[i]);
LCM = (temp * arr[i]) / GCD;
}
printf("GCD IS %d AND LCM IS %d", GCD, LCM);
}
int findGCD(int num1, int num2) {
if (num2 == 0) {
return num1;
}
if (num1 % num2 == 0) {
return num2;
}
return findGCD(num2, num1 % num2);
}

Does this help? Or was your aim to calculate GCD and LCM while calling findGCD as few times as possible?
int main(){
int arr[10]={10,20,30,40,50,60,70,80,90,100};
int GCD=arr[0];
int LCM=arr[0];
int i;
for(i=1;i<sizeof(arr)/sizeof(arr[0]);i++){
GCD = findGCD(GCD,arr[i]);
LCM = (LCM * arr[i]) / findGCD(LCM, arr[i]);
}
printf("GCD IS %d AND LCM IS %d",GCD,LCM);
}

The above formula mentioned by you is true only for two numbers not multiple numbers(in your case 10). The correct formula say for 3 numbers is:
lcm(a,b,c)=abc/gcd(ab,bc,ca)
For more info refer this https://math.stackexchange.com/questions/319297/gcd-to-lcm-of-multiple-numbers

There are multiple problems in your code:
you compute the LCM for all elements of the array, but the GCD only for the 2 initial values.
multiplication formula might overflow before you divide by the GCD. You should perform the operation in the opposite order and still check for potential overflow.
the prototype for findGCD is incorrect: it returns an int.
Here is a corrected version:
#include <limits.h>
#include <stdio.h>
int findGCD(int num1, int num2) {
if (num2 == 0) {
return num1;
}
if (num1 % num2 == 0) {
return num2;
}
return findGCD(num2, num1 % num2);
}
int main() {
int arr[10] = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 };
int GCD = arr[0];
int LCM = arr[0];
size_t i;
for (i = 1; i < sizeof(arr) / sizeof(arr[0]); i++) {
if (LCM == 0 || arr[i] == 0) {
LCM = 0;
break;
}
GCD = findGCD(GCD, arr[i]);
LCM = LCM / findGCD(LCM, arr[i]);
if (arr[i] > INT_MAX / LCM) {
printf("integer overflow: the LCM exceeds the range of type int\n");
return 1;
}
LCM = LCM * arr[i];
}
printf("GCD IS %d AND LCM IS %d", GCD, LCM);
return 0;
}

#include <stdio.h>
#include <stdlib.h>
#define VSTUP "cisla.txt"
#define VYSTUP "vystup.txt"
int nsd(int x,int y){
int delitel = (x < y) ? x : y;
while(x % delitel != 0 || y % delitel != 0)
delitel--;
return delitel;
}
int nsn(int x,int y){
int nasobek = (x > y) ? x : y;
while(nasobek % x != 0 || nasobek % y != 0)
nasobek += (x > y) ? x : y;
return nasobek;
}
int main(int argc, char** argv) {
FILE * vstup;
FILE * vystup;
int c1, c2;
int i = 1, j = 1;
vstup = fopen (VSTUP,"r");
if (vstup == NULL){
printf("Soubor %s nebyl otevren.\n",VSTUP);
return (EXIT_FAILURE);
}
vystup = fopen (VYSTUP,"w");
printf("Vypis cisel ze souboru %s\n-------------------------------- \n",VSTUP);
fprintf(vystup,"Vypis delitelnych cisel ze souboru %s\n--------------------------------------------\n",VYSTUP);
printf("%7s%7s%7s%7s%7s\n","poradi","cislo1","cislo2","nsn","nsd");
fprintf(vystup,"%7s%7s%7s%7s%7s\n","poradi","cislo1","cislo2","nsn","nsd");
while (fscanf(vstup,"%d %d",&c1,&c2) == 2){
printf("%6d.%7d%7d%7d%7d\n",i,c1,c2,nsn(c1,c2),nsd(c1,c2));
if (nsd(c1,c2) != 1){
fprintf(vystup,"%6d.%7d%7d%7d%7d\n",j,c1,c2,nsn(c1,c2),nsd(c1,c2));
j++;
}
i++;
}
printf("\nSoubor %s obsahuje %d dvojic cisel.\n\n",VSTUP,i-1);
fprintf(vystup,"\nSoubor %s obsahuje %d dvojic cisel.\n",VYSTUP,j-1);
if (fclose (vstup) == EOF)
printf("Soubor %s nebyl uzavren.\n",VSTUP);
if (fclose (vystup) == EOF)
printf("Soubor %s se nepovedlo vytvorit.\n",VYSTUP);
else
printf("Byl vytvoren soubor delitelnych cisel %s.\n\n",VYSTUP);
return (EXIT_SUCCESS);
}
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define VSTUP "cisla.txt"
#define VYSTUP "vystup.txt"
int mocnina (int z, int e){
int v = 1;
for(;e > 0;e--)
v *= z;
return v;
}
int prvocislo(int n){
int i;
for(i = 2; i <= sqrt(n); ++i) {
if (n % i == 0)
return 0;
}
return 1;
}
int main(int argc, char** argv) {
FILE * vstup;
FILE * vystup;
int z,e;
int i = 1, j = 1;
vstup = fopen (VSTUP,"r");
if (vstup == NULL){
printf("Soubor %s nebyl otevren.\n",VSTUP);
return (EXIT_FAILURE);
}
vystup = fopen (VYSTUP,"w");
printf("Vystup cisel ze souboru %s\n",VSTUP);
printf("---------------------------------\n");
printf("%6s%9s%9s%9s\n","poradi","zaklad","exponent","mocnina");
fprintf(vystup,"Vystup cisel s prvociselnym zakladem ze souboru %s\n",VYSTUP);
fprintf(vystup,"---------------------------------------------------------\n");
while( fscanf (vstup,"%d %d",&z,&e) == 2){
printf("%5d.%9d%9d%9d\n",i,z,e,mocnina(z,e));
if (prvocislo(z)){
fprintf(vystup,"%5d.%8d%8d%8d\n",j,z,e,mocnina(z,e));
j++;
}
i++;
}
fprintf(vystup,"Soubor %s obsahuje %d dvojic cisel.\n",VYSTUP,j-1);
if (fclose (vstup) == EOF)
printf("Soubor %s nebyl uzavren.\n",VSTUP);
if (fclose (vystup) == EOF)
printf("Soubor %s se nepovedlo vytvorit.\n\n",VYSTUP);
else
printf("\nByl vytvoren soubor cisel %s s poctem dvojic cisel rovnym %d.\n\n",VYSTUP,j-1);
return (EXIT_SUCCESS);
}

Related

Incorrect calculations of averages

I have this super simple code for calculating averages of given even and odd numbers, until the user gives 0. (I would use for loop but we can't).
I'm having a really strange problem with program rounding results like 25/2 is 2.00000. Sorry if this question is stupid but I just can't find a problem.
What am I doing completely wrong?
#include <stdio.h>
#include <stdlib.h>
void funkcja()
{
int sumaNiep = 0;
int sumaPa = 0;
int userInput = 1;
int i = 0;
while(userInput != 0)
{
//wprow zmiennej
printf("%d. Podaj calkowita liczbe: ", i+1);
scanf("%d", &userInput);
//jesli parzysta
if (userInput % 2 == 0)
{
sumaPa += userInput;
} else {
sumaNiep += userInput;
}
i++;
}
double sredniaNiep = sumaNiep/(i-1);
double sredniaPa = sumaPa/(i-1);
printf("\nsrednia parzysta %d / %d : %lf", sumaPa, i, sredniaPa);
printf("\nsrednia parzysta %d / %d : %lf", sumaNiep, i, sredniaNiep);
}
int main()
{
funkcja();
}
The problem is that you do an integer division at the end.
You should break out of the loop if the user enters 0 and make at least one operand a double when you do the division. You also need to count the number of evens and odds:
#include <stdio.h>
#include <stdlib.h>
void funkcja() {
int sumaNiep = 0;
int sumaPa = 0;
int userInput = 1;
int iPa = 0;
int iNiep = 0;
int i = 0;
while(1) {
printf("%d. Podaj calkowita liczbe: ", ++i);
if(scanf(" %d", &userInput) != 1 || userInput == 0) break; // break out
// jesli parzysta
if(userInput % 2 == 0) {
sumaPa += userInput;
++iPa; // count evens
} else {
sumaNiep += userInput;
++iNiep; // count odds
}
}
if(iPa) { // avoid div by zero
double sredniaPa = (double)sumaPa / iPa; // double div
printf("srednia parzysta %d / %d : %lf\n", sumaPa, iPa, sredniaPa);
}
if(iNiep) { // avoid div by zero
double sredniaNiep = (double)sumaNiep / iNiep; // double div
printf("srednia parzysta %d / %d : %lf\n", sumaNiep, iNiep, sredniaNiep);
}
}
The problem was I divided by the number of all digits (odd and even) to calculate both averages. Here is improved code:
#include <stdio.h>
#include <stdlib.h>
void funkcja()
{
int sumaNiep = 0;
int sumaPa = 0;
int userInput = 1;
int i_p = 0, i_np = 0;
while(userInput != 0)
{
//wprow zmiennej
printf("%d. Podaj calkowita liczbe: ", i_p+i_np+1);
scanf("%d", &userInput);
//jesli parzysta
if (userInput % 2 == 0)
{
sumaPa += userInput;
if (userInput != 0)
{
i_p++;
}
} else {
sumaNiep += userInput;
i_np++;
}
}
if (i_np != 0)
{
double sredniaNiep = sumaNiep/(i_np);
printf("\nSrednia nieparzysta %d / %d : %lf", sumaNiep, i_np, sredniaNiep);
}
if (i_p != 0)
{
double sredniaPa = sumaPa/(i_p);
printf("\nSrednia parzysta %d / %d : %lf", sumaPa, i_p, sredniaPa);
}
}
int main()
{
funkcja();
}

Determining the largest non-whole number in C language

I'm trying to make a program that accepts 4 numbers, regardless if it is a whole or non-whole number. It will determine the largest non-whole number found in the inputs. If there are no non-whole numbers present, then it will print a message that there are none.
Here is my code:
#include <stdio.h>
int main()
{
float num1, num2, num3, num4;
//Enter Numbers
printf("Enter 4 Numbers : ");
scanf("%f %f %f %f", &num1, &num2, &num3, &num4);
//Numbers are Integer
if ((num1 - (int) num1) == 0
&& (num2 - (int) num2) == 0
&& (num3 - (int) num3) == 0
&& (num4 - (int) num4) == 0) {
printf("Output : No Non-Whole Numbers found\n");
} else {
//Numbers are Float
if (num1 > num2 && num1 > num3 && num1 > num4) {
printf("Output : %.1f\n", num1);
} else if (num2 > num1 && num2 > num3 && num2 > num4) {
printf("Output : %.1f\n", num2);
} else if (num3 > num1 && num3 > num2 && num3 > num4) {
printf("Output : %.1f\n", num3);
} else {
printf("Output : %.1f\n", num4);
}
}
}
But I have some problems with it, for example when a user inputs:
Enter 4 Numbers : 12.5 15 2 1
Output: 15
Instead it should be 12.5
Enter 4 Numbers : 10.5 10.5 7 8
Output: 8.0
Instead it should be 10.5
As Nils Martel pointed out this should be coded as a loop over an array.
The only difference from his implementation is that I think mine is easier to understand, because it's closer to the original code
#include <stdio.h>
#include <stdlib.h>
#define FALSE (0 != 0)
#define TRUE (!FALSE)
#define ABS(x) ((x >= 0) ? (x) : (-x))
#define NUMS 4
int is_whole(float num)
{
return (ABS(num) - (int)ABS(num)) == 0;
}
int main()
{
float nums[NUMS];
int contains_float = FALSE;
int largest = 0; // Initialized with the first element
//Enter Numbers
printf("Enter 4 Numbers : ");
scanf("%f %f %f %f", &nums[0], &nums[1], &nums[2], &nums[3]);
//Numbers are Integer
for (int i = 0; i < NUMS; ++i) {
if (is_whole(nums[i]) == FALSE) {
contains_float = TRUE;
// The additional condition here accounts for the case when
// nums[0] is the largest element in the array
if (nums[i] > nums[largest] || is_whole(nums[largest]))
largest = i;
}
}
if (contains_float)
printf("Output : %.1f\n", nums[largest]);
else
printf("Output : No Non-Whole Numbers found\n");
}
You can run it here https://onlinegdb.com/rkVwPZaZu
I think the best check for determining, if a number is non while would be
floor(n) != n
Now, In your code you repeat yourself quite often and your logic gets quite complex and hard to understand by just looking at it.
You might find this exercise a great moment, to learn more about arrays and loops!
I've tried to rewrite your code using the floor(n) != n check, and by using arrays and loops. Mind, my C is a little rusty, but I hope you can reason with my code:
#include <stdio.h>
#include <math.h>
void print_largest_non_while(float *numbers, int length) {
int is_set = 0;
float greatest;
for (int i = 0; i < length; i++) {
float n = numbers[i];
if (floor(n) != n) {
// n is a non while number
if (!is_set) {
is_set = 1;
greatest = n;
continue;
}
if (greatest < n) greatest = n;
}
}
if (is_set) printf("%f\n", greatest);
}
int main() {
float num[4];
// Enter Numbers
printf("Enter 4 Numbers : ");
scanf("%f %f %f %f", num, num + 1, num + 2, num + 3);
print_largest_non_while(num, 4);
}
Your test consider that all your numbers are not integers, or that they are all integers. Also consider that the test num1 - (int)num1) == 0 could give false results. Better: compare the abs of the difference to a threshold.
#define N 4
#include <stdio.h>
#include <math.h>
int main(){
float num[N];
//Enter Numbers
printf("Enter %d Numbers : ", N);
for (int i = 0; i < N; ++i) {
int t = scanf ("%f", &num[i]);
if (t != 1) return 1;
}
float eps = 1.0e-5;
int found = 0;
float vmax;
for (int i = 0; i < N; ++i) {
int check = fabs(num[i] - rint(num[i])) > eps;
found += check;
if (check) {
if (found == 1) {
vmax = num[i];
} else {
if (num[i] > vmax) {
vmax = num[i];
}
}
}
}
//Numbers are all Integer if found == 0
if(found == 0) {
printf("Output : No Non-Whole Numbers found\n");
} else {
printf("Output : %.1f\n", vmax);
}
return 0;
}

why when I input any number between 14 and 20, the output is incorrect?

'I need to calculate and print an upside down pascal triangle, so I wrote down 2 functions for factorial and for the nCr, and I have followed, the equation x! / (y! * (x - y)!)'
#include <stdio.h>
#include <stdlib.h>
int Factorial (int value)
{
if (value == 1 || value == 0)
{
return 1;
}
return value*Factorial(value - 1);
}
int nCr(int value, int r)
{
return Factorial(value)/(Factorial(r) * Factorial(value - r));
}
int main(int argc, char **argv)
{
int value, i, j, k;
char* p;
value = strtol(argv[1], &p, 10);
if (*p != '\0')
{
return 1;
}
if (argc != 2)
{
return 1;
}
if (value < 1 || value > 20)
{
printf("Error: Please enter a value between 1 and 20 inclusively\n");
return 1;
}
else
'The problem is supposed to be in the nested loops I guess'
{
for (i = value - 1; i >= 0; i--)
{
for (j = value - i; j > 0; j--)
{
printf(" ");
}
for (k = 0; k <= i; k++)
{
printf("%d ", nCr(i, k));
}
printf("\n");
}
}
return 0;
}
The problem was in the declaration of the Factorial functions, as int type would overflow if the input is more than 13!, so we should declare the Factorial function as long, so that it does not overflow.

I can not determine if it is a prime number

The below program correctly outputs the divisors of the input numbers, but it does not correctly report whether the inputs are prime. For example, when the input is 13, it does not print "The number you entered is a prime number." What's wrong with it?
#include <stdio.h>
#include <stdbool.h>
int main(void)
{
int num;
bool isPrime = true;
printf("Enter a number: ");
while (scanf("%d", &num) == 1)
{
for (int i = 2; i * i <= num; ++i)
{
if (num % i == 0)
{
if (i * i != num)
{
printf("%d ve %d, divides %d\n", i, num / i, num);
}
else
{
printf("%d divides %d.\n", i, num);
}
isPrime = false;
}
}
}
if (isPrime)
{
printf("The number you entered is a prime number.");
}
return 0;
}
the reason is that scanf is in a while loop if there's a valid input but you are checking & printing if it's prime outside of the loop... if you expect this program just get one input and validate it once, then you just need to change that while to if:
#include <stdio.h>
#include <stdbool.h>
int main(void)
{
int num;
bool isPrime = true;
printf("Enter a number: ");
if (scanf("%d", &num) == 1)
{
for (int i = 2; i * i <= num; ++i)
{
if (num % i == 0)
{
if (i * i != num)
{
printf("%d ve %d, divides %d\n", i, num / i, num);
}
else
{
printf("%d divides %d.\n", i, num);
}
isPrime = false;
}
}
}
if (isPrime)
{
printf("The number you entered is a prime number.");
}
return 0;
}
If you expect this program goes in a loop to keep on getting input and validating if it's prime or not, this should do the job:
#include <stdio.h>
#include <stdbool.h>
int main(void)
{
int num;
bool isPrime = true;
while (1)
{
isPrime=true;
printf("Enter a number: ");
if (scanf("%d", &num) == 1)
{
for (int i = 2; i * i <= num; ++i)
{
if (num % i == 0)
{
if (i * i != num)
{
printf("%d ve %d, divides %d\n", i, num / i, num);
}
else
{
printf("%d divides %d.\n", i, num);
}
isPrime = false;
}
}
}
if (isPrime)
{
printf("The number you entered is a prime number.\n");
}
}
return 0;
}
You have missed 2 things !
You should have printed inside the while loop !
In addition to that you didn't change the status of isPrime=true; !
Hope this answers your question !
#include <stdio.h>
#include <stdbool.h>
int main(void)
{
int num;
bool isPrime = true;
while (scanf("%d", &num) == 1)
{
for (int i = 2; i * i <= num; ++i)
{
if (num % i == 0)
{
if (i * i != num)
{
printf("%d ve %d, divides %d\n", i, num / i, num);
}
else
{
printf("%d divides %d.\n", i, num);
}
isPrime = false;
}
}
if (isPrime)
{
printf("The number you entered is a prime number.\n");
}
isPrime=true;
}
return 0;
}
When you entered a prime number, your while loop doesn't break. Try it:
#include <stdio.h>
#include <stdbool.h>
int main(void) {
int num;
bool isPrime = true, finishIt = false;
printf("Enter a number: ");
while (1) {
while (1) {
if (scanf("%d", &num) != 1)
continue;
if (num == 0) {
finishIt = true;
break;
}
int i;
for (i = 2; i * i <= num; ++i) {
if (num % i == 0) {
if (i * i != num) {
printf("%d ve %d, divides %d\n", i, num / i, num);
} else {
printf("%d divides %d.\n", i, num);
}
isPrime = false;
}
}
if (i * i >= num)
break;
}
if (isPrime) {
printf("The number you entered is a prime number.");
}
isPrime = true;
if (finishIt)
break;
}
return 0;
}

BackTracking in C Sum of prime numbers?

I want to make a backtracking program to calculate the sum of every prime number smaller then n. Can you help me doing that ? I was working on a code but I do not know why it is not working ! Thx in advance !
I think I`m doing something wrong !
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int v[20],n;
void afisare(int k)
{
int i;
for(i=0;i<=k;i++)
{
printf("%d",v[i]);
}
}
int valid(int k)
{
int i,prim=0;
for(i=1;i<k;i++)
{
if(v[k]%i==0)
{
prim++;
}
}
if(prim==2)
{
return 1;
}
else
{
return 0;
}
}
void backtr(int k)
{
int val;
for(val=1;val<=n;val++)
{
v[k]=val;
if(valid(k))
{
if(k<n-1)
{
afisare(k);
}
else
{
backtr(k+1);
}
}
}
}
int main()
{
int n;
printf("n=");
scanf("%d",&n);
backtr(1);
return 0;
}
A bit late but I hope to help someone else
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int verify(int s) {
if (s == 0)
return 0;
else if (s == 1)
return 1;
else
int z = 0;
int i = 1;
while (i <= s) {
if (s % i == 0)
z++;
i++;
}
if (z == 2)
return s;
else
return 0;
}
int backback(int n, int s, int *sum) {
if (s == n) {
return;
}
int z = verify(s);
*sum = *sum + z;
backback(n, s + 1, sum);
return *sum;
}
int back(int n) {
if (n <= 0)
return 0;
else if (n == 1)
return 1;
else
int sum = 0;
int x = backback(n, 0, &sum);
return x;
}
int main(void) {
int n;
printf("Insert an integer number: \t");
scanf("%d", &n);
int x = back(n);
if (x == 0)
printf("\nInvalid number");
else if (x == 1)
printf("\nThe sum of prime numbers of the number %d is: \t%d", n, x);
else
printf("\nThe sum of prime numbers of the number %d is: \t%d", n, x);
return 0;
}

Resources