I have created a code for finding LCM of two nos. I think that the code is correct but I have an undesired output. What ks the problem in this code?
#include<stdio.h>
#include<conio.h>
main()
{
int i, j, a, b, lcm;
printf("Enter two nos : ");
scanf("%d %d", &a, &b);
for(i=1; i<=b; i++)
{
for(j=1; j<=a; j++)
{
if(a*i==b*j)
{
lcm=a*i;
break;
}
}
}
printf("LCM=%d", lcm);
getch();
}
The LCM of two numbers a,b is at least max(a,b) and at most a*b, so your first idea about the boundaries is correct. But if you take a closer look to one of the definitions of LCM (of two positive integers) a and b you'll find that the LCM is the smallest number such that LCM % a = 0 and LCM % b = 0 where "%" means "remainder of integer division, truncating" and that is exactly what you can use here.
Example:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int a, b, lcm;
printf("Enter two nos : ");
scanf("%d %d", &a, &b);
/* TODO: checks and balances! */
/* Set lcm to the larger of the two numbers */
lcm = (a < b) ? b : a;
/* check if both "a" and "b" divide "lcm" without a remainder
* otherwise increment "lcm" */
for (;;) {
if ((lcm % a == 0) && (lcm % b == 0)) {
/* we got the LCM, break out of loop */
break;
}
/* Otherwise increment "lcm" by one */
lcm++;
}
printf("LCM = %d\n", lcm);
exit(EXIT_SUCCESS);
}
There are more elegant and more general methods but I think the example above is quite easy to follow.
Related
In the above mentioned I wanted to ask that what I have done wrong in my code I have tried debugging it many times but was not able to understand the logical error in my code.
Any help would be appreciated.
#include <stdio.h>
#include <math.h>
int digit(int n);
int digit(int n) {
int a;
double i = 0;
do {
a = n % (int)(pow(10, i));
i++;
} while (a != n);
return i;
}
void is_armstrong(int n);
void is_armstrong(int n) {
int a, b;
double sum;
for (int i = 0; i < digit(n); i++) {
a = n / (int)pow(10, (double)i);
b = a % 10;
sum += pow((double)b, 3);
}
if ((int)sum == n) {
printf("%d is an armstrong number.\n", n);
}
}
int main() {
int a, b;
printf("Please input the left hand limit of range : \n");
scanf(" %d", &a);
printf("Please input the right hand limit of range : \n");
scanf(" %d", &b);
for (int i = a; i <= b; i++) {
is_armstrong(i);
}
is_armstrong(153);
return 0;
}
This code is not even showing 153 an Armstrong number.
Noting the comments about using the power function and what your ultimate outcome is in identifying Armstrong numbers over a given range, I did a bit of refactoring to simplify the process in identifying such numbers. Following is the code snippet that provides the functionality.
#include <stdio.h>
void is_armstrong(int n) {
int a, b, c, d;
int sum = 0;
a = n;
c = 0;
while (a != 0) /* Determine the number of digits to raise to a power */
{
a = a / 10;
c = c + 1;
}
a = n; /* Reset the work number */
while (a != 0) /* Noted from the comments to simplify the test */
{
b = a % 10;
d = b;
for (int i = 1; i < c; i++)
{
d = d * b;
}
sum = sum + d; /* Just mulitply each digit by itself the required number of times */
a = a / 10; /* Divide by 10 along with using the modulo function to evaluate each digit */
}
if (sum == n) {
printf("%d is an armstrong number.\n", n);
}
}
int main() {
int a, b;
printf("Please input the left hand limit of range : \n");
scanf(" %d", &a);
printf("Please input the right hand limit of range : \n");
scanf(" %d", &b);
for (int i = a; i <= b; i++) {
is_armstrong(i);
}
return 0;
}
Following are some key points.
Since the power function is not needed, the math.h include file is not needed and linking the math library is also not needed.
Acquiring each digit is simplified by just utilizing the modulo operation in combination with integer division by "10".
Acquiring the value of each digit raised to the nth power is simplified by just performing a repeated multiplication.
Following is test output at the terminal.
#Dev:~/C_Programs/Console/Armstrong/bin/Release$ ./Armstrong
Please input the left hand limit of range :
1
Please input the right hand limit of range :
10000
1 is an armstrong number.
2 is an armstrong number.
3 is an armstrong number.
4 is an armstrong number.
5 is an armstrong number.
6 is an armstrong number.
7 is an armstrong number.
8 is an armstrong number.
9 is an armstrong number.
153 is an armstrong number.
370 is an armstrong number.
371 is an armstrong number.
407 is an armstrong number.
1634 is an armstrong number.
8208 is an armstrong number.
9474 is an armstrong number.
And as a confirmation, it can be seen that the value "153" was recognized as an Armstrong number.
Give the code snippet a try and see if it meets the spirit of your project.
There is no need to count the number of digits in n, you can just sum the cubes of each digit, one at a time dividing the number by 10 at each iteration.
Here is a simplified version:
#include <stdio.h>
void is_armstrong(int n) {
int sum = n;
while (n != 0) {
int b = n % 10;
n /= 10;
sum -= b * b * b;
}
return sum == 0;
}
int main() {
int a, b;
printf("Please input the left hand limit of range:\n");
if (scanf("%d", &a) != 1)
return 1;
printf("Please input the right hand limit of range:\n");
if (scanf("%d", &b) != 1)
return 1;
for (int i = a; i <= b; i++) {
if (is_armstrong(i)) {
printf("%d is an Armstrong number.\n", i);
}
}
return 0;
}
Using a recurrence function ,find a program that computes the multiplication of two numbers using addition operator.
What I found is as follows:
/*C program to multiply two numbers using plus operator.*/
#include <stdio.h>
int main()
{
int a,b;
int mul,loop;
printf("Enter first number: ");
scanf("%d",&a);
printf("Enter second number: ");
scanf("%d",&b);
mul=0;
for(loop=1;loop<=b;loop++){
mul += a;
}
printf("Multiplication of %d and %d is: %d\n",a,b,mul);
return 0;
}
However I'm not sure if the it uses a recurrence function,can someone check that and if it does use a recursive function then show me how to do that?
This simple logic should work for you:
int multiply(int a, int b)
{
if(a < b)
return multiply(b, a); // swap
else if(b != 0)
return (a + multiply(a, b - 1)); // recursion
else
return 0;
}
I wanted to fix my code to create random operation here, what should I fix here?
#include <stdio.h>
int main()
{
int x,y,z,a;
char o;
while(1)
{
printf("give your three numbers: ");
scanf("%d %d %d",&x,&y,&z);
printf("(%d*%d-%d) what is the correct among following answers? \n 1. %d\n 2. %d\n 3. %d\n ",
x,y,z,x*y-z,x*y*z,x-y*z);
printf("what is answer? \n: ");
scanf("%d",&a);
if(a == 1)
{
printf("you are right!\n");
}
else
{
printf("you are false!\n\n");
}
getchar();
printf("Would you like to exit programm? (y/n) : ");
scanf("%c",&o);
if (o=='Y' || o=='y')
{
break;
}
else if(o=='N' || o=='n')
{
continue;
}
else
{
printf("Wrong input!!!!");
}
return 0;
}
}
What I mean is I want to try change operation such as * + - randomly when I run code, and also along with this question, the answer should be changed...
thank you!
Your question is mainly focused on shuffling the answers. By studying from couple of sites I have found an solution for this. This is little bit difficult but studying the code few times you can get it
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
void randomize(int arr[], int n) {
srand(time(NULL));
int i;
for(i = n-1; i > 0; i--) {
int j = rand() % (i+1);
swap(&arr[i], &arr[j]);
}
}
int main() {
int x,y,z,a;
int i;
int a1, a2, a3;
int arr[] = {1, 2, 3};
int n = sizeof(arr)/ sizeof(arr[0]);
printf("give your three numbers: ");
scanf("%d %d %d",&x,&y,&z);
a1 = x*y-z;
a2 = x*y*z;
a3 = x-y*z;
printf("Before shuffle = %d %d %d\n\n", a1, a2, a3);
char answers[] = {a1, a2, a3};
printf("(%d*%d-%d)what is the correct among following answers?\n", x, y, z);
randomize (arr, n);
for(i=0; i<n; i++) {
int index = arr[i];
printf("%2d - %d\n", i+1, answers[index]);
}
return 0;
}
This is the outputs
First time run
give your three numbers: 2
2
2
Before shuffle = 2 8 -2
(2*2-2)what is the correct among following answers?
1 - 8
2 - 2
3 - -2
Second time run
give your three numbers: 2
2
2
Before shuffle = 2 8 -2
(2*2-2)what is the correct among following answers?
1 - -2
2 - 8
3 - 2
You can try this multiple times. Every time answers will be shuffle. This is the Source I have referred.
Just provide one of examples here. There are many kinds way to implement. In the random operation generation part. I would like to write a random number generator function, which purpose is to generate the given range of random number.
int gen_random(int min, int max)
{
srand( time(NULL) );
return rand() % (max - min + 1) + min;
}
In order to represent four operator (+, -, *, /), The number (let's call the operation number) 1 to 4 is used for represent four operator respectively. The calculation function map the operation number to operation and get the result.
int calculation(int number1, int number2, int op)
{
switch(op)
{
case 1:
return number1 + number2;
case 2:
return number1 - number2;
case 3:
return number1 * number2;
case 4:
return number1 / number2;
}
}
You can use the gen_random and the calculation function above to change operation randomly. The usage of the gen_random and the calculation function is something like:
int op = gen_random(1, 4); // Generate operation randomly
printf("%d\n", op);
printf("%d\n", calculation(x, y, op)); // Pass x, y, and operation number into calculation function to get answer
I'm a newbie!
I'm supposed to get 2 integers from the user, and print the result(sum of all numbers between those two integers).
I also need to make sure that the user typed the right number.
The second number should be bigger than the first one.
And if the condition isn't fulfilled, I have to print "The second number should be bigger than the first one." and get the numbers from the user again until the user types right numbers that meet the condition.
So if I programmed it right, an example of the program would be like this.
Type the first number(integer) : 10
Type the second number(integer) : 1
The second number should be bigger than the first one.
Type the first number(integer) : 1
Type the second number(integer) : 10
Result : 55
End
I think that I have to make two loops, but I can't seem to figure out how.
My English is limited, to help your understanding of this quiz, I'll add my flowchart below.
I tried many different ways I can think of, but nothing seems to work.
This is the code that I ended up with now.
But this doesn't work either.
#include <stdio.h>
void main(void)
{
int a = 0;
int b = 0;
int total_sum = 0;
printf("Type the first number : \n");
scanf("%d", &a);
printf("Type the second number : \n");
scanf("%d", &b);
while (a > b) {
printf("The second number should be bigger than the first one.\n");
printf("Type the first number : \n");
scanf("%d", &a);
printf("Type the second number : \n");
scanf("%d", &b);
}
while (a <= b) {
total_sum += a;
a++;
}
printf("Result : \n", total_sum);
}
Instead of using loop to sum the numbers, we can use mathematical formula.
Sum of first N integers= N*(N+1)/2
#include <stdio.h>
int main(void)
{
int a = 0;
int b = 0;
int sum;
//Run infinite loop untill a>b
while(1)
{
printf("Type the first number : ");
scanf("%d", &a);
printf("Type the second number : ");
scanf("%d", &b);
if(a>b)
{
printf("The second number should be bigger than the first one.\n");
}
else
{
break;
}
}
//Reduce comlexity of looping
sum=((b*(b+1))-(a*(a-1)))/2;
printf("Result : %d " , sum);
return 0;
}
After corrections your code should run. The community has pointed out many mistakes in your code. Here's an amalgamated solution:
#include <stdio.h>
int main(void)
{
int a = 0;
int b = 0;
int correctInput=0;
int total_sum = 0;
do
{
printf("Type the first number : \n");
scanf("%d", &a);
printf("Type the second number : \n");
scanf("%d", &b);
if(a<b)
correctInput=1;
else
printf("The second number should be bigger than the first one.\n");
}
while (correctInput ==0) ;
while (a <= b) {
total_sum += a;
a++;
}
printf("Result : %d \n" , total_sum);
return 0;
}
Factorials are used frequently in probability problems. The factorial of a positive integer n (written n! and pronounced "n factorial") is equal to the product of the positive integers from 1 to n: n! = 1 x 2 x 3 x x n Write a program that takes as input an integer n and computes n!.
incredibly new to programming I am receiving an error on line 12 stating that my break statement is not in the loop or switch. Can anyone explain where my error is and how to fix it?
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
int n1, n2, i, gcd, lcm;
printf("Enter two positive integers: ");
scanf("%d %d",&n1,&n2);
for(i=1; i <= n1 && i <= n2; ++i) {
printf("Enter two positive integers: ");
scanf("%d %d",&n1,&n2);
if(n1==-1,n2==-1) break;
// Checks if i is factor of both integers
if(n1%i==0 && n2%i==0)
gcd = i;
}
lcm = (n1*n2)/gcd;
printf("The LCM of two numbers %d and %d is %d.", n1, n2, lcm);
return 0;
}
If you are "receiving an error on line 12 stating that my break statement is not in the loop or switch" then either you have a very deficient compiler or you've posted the wrong code. That code has a few problems but a break in the wrong place is not one of them.
That particular error message often occurs when you've mislaid some braces, along the lines of:
int i;
for (i = 0; i < 10; ++i)
printf("%d\n", i);
if (someCondition)
break;
That's because, despite the fact it looks like you're breaking out of a loop, the actual break statement is not within the loop. Only the printf is.
In terms of the code you have provided, there are numerous ways to clean it up:
Remove unneeded includes.
Refactor out the number input to a common function.
Allow a single non-positive number to terminate the program.
Use DRY principle for input, there's really any need to duplicate code segments if you structure it corretly.
Make input more robust, allowing for invalid numbers.
Add more comments, these will greatly assist you (or others who have to maintain your code) in the future.
Use better variable names. Other than i for small localised loops, I almost never use single-character variable names.
Fix the if(n1==-1,n2==-1) bit. That doesn't do what you appear to think it does. The comma operator will evaluate both expressions but the result of the full expression is the rightmost one. So it's effectively if(n2==-1).
To that end, the following is how I would write the code:
#include <stdio.h>
#define ERR_NON_POS -1
#define ERR_INVALID -2
// Gets a single number.
// If non-positive or invalid, returns error (a negative value ERR_*).
// Otherwise, returns the (positive) number.
int getNumber(void) {
int number;
if (scanf("%d", &number) != 1) return -2;
if (number <= 0) return -1;
return number;
}
int main(void) {
// Infinite loop, we'll break from within as needed.
for (;;) {
printf("Enter two positive integers (a negative number will stop): ");
// Do it one at a time so a SINGLE negative number can stop.
int number1 = getNumber();
if (number1 == ERR_INVALID) {
puts("** Non-integral value entered");
break;
}
if (number1 == ERR_NON_POS) break;
int number2 = getNumber();
if (number2 == ERR_INVALID) {
puts("** Non-integral value entered");
break;
}
if (number2 == ERR_NON_POS) break;
// Work out greatest common divisor (though there are better ways
// to do this than checking EVERY possibility).
int gcd = 1;
for (int i = 2; (i <= number1) && (i <= number2); ++i) {
if (number1 % i == 0 && number2 % i == 0) {
gcd = i;
}
}
// Work out the lowest common multiple.
int lcm = number1 * number2 / gcd;
// Print them both and go get more.
printf("For numbers %d and %d, GCD is %d and LCM is %d.\n", number1, number2, gcd, lcm);
}
return 0;
}
And, if you're wondering about the more efficient way of calculating GCD, you should look into Euclid's algorithm. This can be defined as (for non-negative a and b):
gcd(a,b) = a if b is zero
gcd(b, a mod b) if b is non-zero
That means you can have a recursive function:
int gcd(int a, int b) {
if (b == 0) return a;
return gcd(b, a % b);
}
Or an iterative one if you're vehemently opposed to recursion:
int gcd(int a, int b) {
while (b != 0) {
int t = a % b;
a = b;
b = t;
}
return a;
}