I wrote the code for the following program but I don't understand how I can involve a function. The question asks me to use a function that returns the sum of divisors. Please take a look at the question and my code and try to help me out.
THE QUESTION:
Write a C program that finds and prints the sum of divisors for all
the numbers between 101 and 110. The divisors of x are those numbers
x divides without a remainder (e.g. the divisors of number 10 are 1,
2, 5, and 10 and their sum = 1+2+5+10=18, the divisors of number 11
are 1 and 11 and their sum=1+11=12, and so forth).
Your program should also print the number (101 to 110) that has the maximum sum of divisors.
Your program should use at least one function called div_sum that
takes a number and returns its sum of divisors.
MY CODE:
#include <iostream>
#include <stdio.h>
int main()
{
int i=1, x=101, sum, smax=0, xmax=0;
for (x=101; x<=110; x++)
{ sum=0;
for(i=1; i<=x; i++)
{
if(x%i==0)
sum+=i;
}
if(sum>smax)
{
smax=sum;
xmax=x;
}
printf("The sum of factors of %d = %d\n",x,sum);
}
printf("The number that has the maximum sum of divisors is %d with the sum of %d",xmax,smax);
return 0;
}
You can move the loop where you calculate sum of divisors for each x to separate function:
int div_sum(int x) {
int sum = 0;
for(int i=1; i<=x; i++)
{
if(x%i==0)
sum+=i;
}
return sum;
}
and use it in your program:
for (x=101; x<=110; x++)
{
sum= div_sum(x);
if(sum > amax)
...
}
For each number in the loop, call the function. The function should have all the code you currently have in the loop.
Your code is actually really close.
Here's what I did:
void div_sum()
{
int sum;
int max_sum = 0;
int max_num;
for (int x = 101; x <= 110; x++)
{
sum = 0;
for (int i = 1; i <= x; i++)
if (x%i == 0)
sum = sum + i;
printf("\nFor the number %d, the sum of the divisors is %d\n", x, sum);
if (sum > max_sum)
{
max_sum = sum;
max_num = x;
}
}
printf("max = %d\n", max_num);
}
Related
#include <stdio.h>
#include <math.h>
int main() {
int n, count, sum;
printf("Enter upper bound n \n");
scanf("%d", &n);
for (int a = 1; a <= n; a++) {
count = 0;
sum = 0;
for (int i = 2; i <= sqrt(a); ++i) {
if (a % i == 0) {
count++;
break;
}
}
if (count == 0 && a != 1) {
sum = a + sum;
}
}
printf("%d", sum);
}
The program is my attempt to print summation of primes < n. I am getting sum = 0 every time and I am unable to fix this issue.
The reason you do not get the sum of primes is you reset the value of sum to 0 at the beginning of each iteration. sum will be 0 or the value of the n if n happens to be prime.
Note also that you should not use floating point functions in integer computations: i <= sqrt(a) should be changed to i * i <= a.
The test on a != 1 can be removed if you start the loop at a = 2.
Here is a modified version:
#include <stdio.h>
int main() {
int n = 0, sum = 0;
printf("Enter upper bound n: \n");
scanf("%d", &n);
// special case 2
if (n >= 2) {
sum += 2;
}
// only test odd numbers and divisors
for (int a = 3; a <= n; a += 2) {
sum += a;
for (int i = 3; i * i <= a; i += 2) {
if (a % i == 0) {
sum -= a;
break;
}
}
}
printf("%d\n", sum);
return 0;
}
For large values of n, a much more efficient approach would use an array and perform a Sieve of Eratosthenes, a remarkable greek polymath, chief librarian of the Library of Alexandria who was the first to compute the circumference of the earth, 2300 years ago.
Here is an improved version:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
int n = 0;
long long sum = 0;
if (argc > 1) {
sscanf(argv[1], "%i", &n);
} else {
printf("Enter upper bound n: \n");
scanf("%i", &n);
}
// special case 2
if (n >= 2) {
sum += 2;
}
unsigned char *p = calloc(n, 1);
for (int a = 3; a * a <= n; a += 2) {
for (int b = a * a; b < n; b += a + a) {
p[b] = 1;
}
}
for (int b = 3; b < n; b += 2) {
sum += p[b] * b;
}
free(p);
printf("%lld\n", sum);
return 0;
}
Error about sum getting set to zero inside the loop has been already pointed out in previous answers
In current form also, your code will not return zero always. It will return zero if value of upper bound is given as non prime number. If prime number is given as upper bound, it will return that number itself as sum.
As mentioned in comment you should initialize sum before first loop something like
int n, count, sum=0;
or you can initialize sum in the loop like
for(a=1,sum=0;a <= n; a++)
and remove sum=0; inside the first loop because it changes sum to 0 every time first loop executes. You can check this by inserting this lines to your code
printf("Before sum %d",sum);
sum = 0;
printf("After Sum %d",sum);
make sure sure that if you are initializing sum in the loop, define "a" in outer of the loop if not the sum goes to local variable to for loop and it hides the outer sum.
I am trying to find the sum of digits with test cases. But the problem is after I find one sum, this sum is adding to the next sum but I only one particular sum of that numbers' digit. Please help. Here is my code:
#include <stdio.h>
int main() {
int t, n, i, r, sum=0;
scanf("%d", &t);
for(i=0; i<t; i++) {
scanf("%d", &n);
while(n>0) {
r = n % 10;
sum = sum + r;
n = n / 10;
}
printf("%d\n", sum);
}
return 0;
}
And Here is my output:
3
1234
10
2347
26
8744
49
Why my previous sum adding to the next sum? I am not understanding.
My desired output:
3
1234
10
2347
16
8744
23
Problem:
Your variable sum is set to 0 on the start of the program and you are adding the sum of each test case in the same variable without cleaning the result of the previous test case (by setting sum = 0 before the next test case starts.)
Possible Solution:
Initialize your your variable sum before a test case starts.
Code:
for(i=0; i<t; i++)
{
scanf("%d", &n);
sum = 0; //Set sum = 0
//Test Case started in while loop
while(n>0) {
r = n % 10;
sum = sum + r;
n = n / 10;
}
printf("%d\n", sum);
}
In the begining of your loop set sum to 0. So that before taking sum over next set of elements it is reinitialized to zero.
for(i=0; i<t; i++)
{
sum = 0;
scanf("%d", &n);
You need to set your sum=0; on the first line of the for loop.
This the example of Euler's Totient. Euler’s Totient function ?(n) for an input n is count of numbers in {1, 2, 3, …, n} that are relatively prime to n, i.e., the numbers whose GCD (Greatest Common Divisor) with n is 1.
I'm getting struck in the main() function. As per my intuition, it should calculate the sum of every pair of gcd which is equal to 1 for every number.
The output is iterating infinite times when it is entering into the hcf function. If I remove the hcf function just to check whether the pairs which the function is taking are correct, it is printing them in the proper order. But, if I add the hcf() in the main function, it is going into an infinite loop rather printing the sum of gcds of pairs which are equal to 1.
#include<stdio.h>
int temp,a,b,n,sum=0,i,j, gcd;
int hcf(a,b)
{ for(i=1; i <= a && i <= b; i++)
{
if(a%i==0 && b%i==0)
gcd = i;
}
return gcd;
}
void main()
{
printf("Enter the value of n");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
{
printf("%d,%d\n",j,i);
if(hcf(j,i)==temp)
{
sum=sum+1;
}
}
printf("%d\n",sum);
sum=0;
}
}
Root cause analysis:
The problem is you are incrementing i (with global scope) in 2 places: 1. for loop in main. 2. for loop in hcf. The result is j in the for loop inside main never reaches i and you get an infinite loop.
Solution Description:
A possible correction is to limit the scope of i inside hcf:
#include "stdio.h"
int temp,a,b,n,sum=0,i,j, gcd;
int hcf(int a, int b)
{
int i;
for (i = 1; i <= a && i <= b; i++)
{
if (a % i == 0 && b % i == 0)
gcd = i;
}
return gcd;
}
int main()
{
printf("Enter the value of n");
scanf_s("%d", &n);
for (i = 1; i <= n; i++)
{
for (j = 1; j <= i; j++)
{
printf("%d,%d\n", j, i);
if (hcf(j, i) == temp)
{
sum = sum + 1;
}
}
printf("%d\n", sum);
sum = 0;
}
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int summation(int sum,int Num[],int n) {
if (n < 0) {
return sum;
} else {
printf("%d \n", Num[n]);
sum = Num[n] + summation(sum, Num, n - 1);
}
}
int main () {
int i = 0, j = 0 , k = 0, n = 0;
printf("Enter number of numbers: ");
scanf("%d", &n);
int Num[n];
while (i < n) {
//printf("Enter number %d : ", i);
//scanf("%d", &Num[i]);
Num[i] = 1;
i++;
}
int sum = 0;
sum = summation(sum, Num, n);
printf("The sum is %d \n", sum);
}
The above program runs correctly only with 3
why does it generate only results for 3,3^3, 3^9??
Please help me out here this programs runs only with powers of 3. For now i have calculated 3^1,3^3 and 3^9. For other numbers it returns a wrong value.
You neglect to return a value from the summation function. A good compiler would draw your attention to this fact.
You call summation with n equal to the size of the function, which causes this line:
sum = Num[n] + ...
to read past the end of the array.
These mistakes lead to undefined behavior, which can show odd preferences for powers of three, or anything else.
I'm very new to programming and I was asked to find the sum of prime numbers in a given range, using a while loop. If The input is 5, the answer should be 28 (2+3+5+7+11). I tried writing the code but it seems that the logic isn't right.
CODE
#include <stdio.h>
int main()
{
int range,test;
int sum = 2;
int n = 3;
printf("Enter the range.");
scanf("%i",range);
while (range > 0)
{
int i =2;
while(i<n)
{
test = n%i;
if (test==0)
{
goto end;
}
i++;
}
if (test != 0)
{
sum = sum + test;
range--;
}
end:
n++;
}
printf("The sum is %i",sum);
return 0;
}
It would be nice if you could point out my mistake and possibly tell me how to go about from there.
first of all, in the scanf use &range and not range
scanf("%i",&range);
Second this instruction is not correct
sum = sum + test;
it should be
sum = sum + n;
and also the
while (range > 0)
should be changed to
while (range > 1)
Because in your algorithm you have already put the first element of the range in the sum sum = 2 so the while should loop range - 1 times and not range times
That's all
OK, my C is really bad, but try something like the following code. Probably doesn't compile, but if it's a homework or something, you better figure it out yourself:
UPDATE: Made it a while loop as requested.
#include <stdio.h>
int main()
{
int range, test, counter, innerCounter, sum = 1;
int countPrimes = 1;
int [50] primesArray;
primesArray[0] = 1;
printf("Enter the range.");
scanf("%i",range);
counter = 2;
while (counter <= range) {
for (innerCounter = 1; innerCounter < countPrimes; innerCounter++) {
if (counter % primesArray[innerCounter] == 0)
continue;
primesArray[countPrimes + 1] = counter;
countPrimes ++;
sum += counter;
}
counter ++
}
printf("The sum is %i",sum);
return 0;
}
I haven't done C in a while, but I'd make a few functions to simplify your logic:
#include <stdio.h>
#include <math.h>
int is_prime(n) {
int i;
for (i = 2; i <= sqrt(n); i++) {
if (n % i == 0) {
return 0;
}
}
return 1;
}
int main() {
int range, i, sum, num_primes = 0;
printf("Enter the range: ");
scanf("%d", &range);
for (i = 2; num_primes < range; i++) {
if (is_prime(i)) {
sum += i;
num_primes++;
}
}
printf("The sum is %d", sum);
return 0;
}
Using goto and shoving all of your code into main() will make your program hard to debug.
Copy - pasted from here.
#include <stdio.h>
int main() {
int i, n, count = 0, value = 2, flag = 1, total = 0;
/* get the input value n from the user */
printf("Enter the value for n:");
scanf("%d", &n);
/* calculate the sum of first n prime nos */
while (count < n) {
for (i = 2; i <= value - 1; i++) {
if (value % i == 0) {
flag = 0;
break;
}
}
if (flag) {
total = total + value;
count++;
}
value++;
flag = 1;
}
/* print the sum of first n prime numbers */
printf("Sum of first %d prime numbers is %d\n", n, total);
return 0;
}
Output:
Enter the value for n:5
Sum of first 5 prime numbers is 28
Try the simplest approach over here. Check C program to find sum of all prime between 1 and n numbers.
CODE
#include <stdio.h>
int main()
{
int i, j, n, isPrime, sum=0;
/*
* Reads a number from user
*/
printf("Find sum of all prime between 1 to : ");
scanf("%d", &n);
/*
* Finds all prime numbers between 1 to n
*/
for(i=2; i<=n; i++)
{
/*
* Checks if the current number i is Prime or not
*/
isPrime = 1;
for(j=2; j<=i/2 ;j++)
{
if(i%j==0)
{
isPrime = 0;
break;
}
}
/*
* If i is Prime then add to sum
*/
if(isPrime==1)
{
sum += i;
}
}
printf("Sum of all prime numbers between 1 to %d = %d", n, sum);
return 0;
}