I was wondering, how can I add up the divisors displayed once I run my code?
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, i;
scanf("%d", &n);
for(i = 1; i < n; i++)
{
if(n % i == 0)
{
printf("%d\n", i);
}
}
return 0;
}
If I were to enter, say, 25, it would print out 1, 5. I was wondering how to add up the two numbers 1 and 5?
Could it be as simple as this? You will want to use a simple increment operator (+=), to increment the variable sum.
int main(void)
{
int n, i, sum = 0;
if( scanf("%d", &n)!= 1){
fprintf(stderr,"Error in input\n");
exit(EXIT_FAILURE);
}
for(i = 1; i < n; i++)
{
if(n % i == 0)
{
printf("%d\n", i);
sum += i;
}
}
printf("Sum of divisors: %d\n", sum);
return 0;
}
How to add up divisors of an integer n?
Iterating n times as with for(i = 1; i < n; i++) can take a long time when n is some high value, especially if code used 64-bit integers. Instead only iterate sqrt(n) times - much faster
int factor_count(int number) {
if (number <= 1) {
return TBD_Code(number); // OP needs to define functionality for these cases.
}
int sum = 1;
int quotient;
int divisor = 1;
do {
divisor++;
quotient = number/divisor;
int remainder = number%divisor;
if (remainder == 0) {
sum += divisor;
if (quotient > divisor) sum += quotient;
}
} while (divisor < quotient);
return sum;
}
Additional improvements noted here.
Related
Given some natural numbers n and k, my goal is to write a C program that outputs a number formed by every k-th digit of n. I wrote a program as follows:
#include <stdio.h>
#include <math.h>
#define MAX 100
void printDigit(int n, int k)
{
int arr[MAX];
int i = 0;
int j, r;
while (n != 0) {
r = n % (int)pow(10,k);
arr[i] = r;
i++;
n = n / pow(10,k);
}
for (j = i - 1; j > -1; j--) {
printf("%d ", arr[j]);
}
}
int main()
{
int n = 12345678;
int k = 2;
printDigit(n,k);
return 0;
}
My code outputs the same number but partitioned into substrings of length k. Why is that and how can I fix it so that I get the number I wanted?
Your logic is too complicated, but if you want to stick to it:
int intpow(int x, int y)
{
int result = 1;
while(y--) result *= x;
return result;
}
void printDigit(int n, int k)
{
int arr[MAX];
int i = 0;
int j, r, powv;
while (n != 0) {
powv = intpow(10,k -1);
n /= powv;
if(!n) break;
r = n % 10;
arr[i] = r;
i++;
n = n / 10;
}
for (j = i - 1; j > -1; j--) {
printf("%d ", arr[j]);
}
}
n % (int)pow(10,k) is the low-order k digits of n. If you just want one digit, use n % 10.
Since pow(10, k) returns a double, it might not be an exact integer. You should round it to the nearest integer to do proper division.
void printDigit(int n, int k)
{
int arr[MAX];
int i = 0;
int j, r;
int divisor = lround(pow(10, k));
while (n != 0) {
r = n % 10;
arr[i] = r;
i++;
n = n / divisor;
}
for (j = i - 1; j > -1; j--) {
printf("%d ", arr[j]);
}
}
Hello i try to make a university exercise that calculate the GCD without math.h library! I have write this code but i can't understand why my code doesn't get in if statement of (min, max) calculation!Seems that the code doesn't give the results that i want an if statement condition! I have try everything! Please any idea what's going on?
#include <stdio.h>
#include <stdlib.h>
#define MAX 1000
int main(void)
{
int n;
int i, j, a;
int counter2 = 0;
int large;
int small;
int rem, gcd;
int max=INT_MIN,min=INT_MAX;
int achilles;
scanf("%d", &n);
printf("%d = ",n);
for (i = 1; i <= n; i++)
{
int count = 0;
for (j = 1; j <= i; j++)
{
if (i % j == 0)
{
count++;
}
}
int l = 0;
if (count == 2)
{
int expo;
while (n % i == 0) // calculate factor and his exponent
{
l++;
n = n / i;
}
expo=l;
if (expo > max) // calculates min and max in order to find GCD
{
max = expo;
large = max;
}
if (expo < max)
{
min = expo;
small = min;
}
}
//large = max;
//small = min;
while (small) { // While small is not 0
// Calculates GCD
rem = large % small;
large = small;
small = rem;
}
//gcd = large;
// printf("GCD(%d,%d)= %d", large, small, gcd);
}
gcd = large;
printf("GCD(%d,%d)= %d", large, small, gcd);
}
I am writing a program in order to count all achilles numbers without the math.h library. In this programm first I calculate powerful numbers after that I calculate GCD of powerful number. If GCD is 1 then the current number is achilles.
My problem is that my program works with scanf() but not with for loop counter! What i am doing wrong?
Thank you very much!
#include <stdio.h>
#define MAX 1000
int main(void)
{
int n;
int i, j, a;
int counter2 = 0;
int large;
int small;
int rem, gcd, max = 1, min = 1;
int achilles;
for (a = 1; a <= MAX; a++) //for loop for counter
{
n=a;
for (i = 1; i <= n; i++)
{
int count = 0;
for (j = 1; j <= i; j++)
{
if (i % j == 0)
{
count++;
}
}
int l = 0;
if (count == 2)
{
while (n % i == 0) // calculate factor and his exponent
{
l++;
n = n / i;
}
if (l > max) // calculates min and max in order to find GCD
{
max = l;
}
if (l < min)
{
min = l;
}
}
large = max;
small = min;
while (small) { // While small is not 0
// Calculates GCD
rem = large % small;
large = small;
small = rem;
}
gcd = large;
// printf("GCD(%d,%d)= %d", large, small, gcd);
}
if (gcd == 1) {
achilles = n;
// printf("%d\n", achilles);
}
// printf("GCD(%d,%d)= %d", max, min, gcd);
printf("%d\n", achilles);
}
}
The programm before editing with the for loop is the following!
#include <stdio.h>
#define MAX 1000
int main(void)
{
int n;
int i, j, a;
int counter2 = 0;
int large;
int small;
int rem, gcd, max = 1, min = 1;
int achilles;
scanf("%d", &n);
printf("%d = ",n);
for (i = 1; i <= n; i++)
{
int count = 0;
for (j = 1; j <= i; j++)
{
if (i % j == 0)
{
count++;
}
}
int l = 0;
if (count == 2)
{
while (n % i == 0) // calculate factor and his exponent
{
l++;
n = n / i;
}
if (l > max) // calculates min and max in order to find GCD
{
max = l;
}
if (l < min)
{
min = l;
}
}
large = max;
small = min;
while (small) { // While small is not 0
// Calculates GCD
rem = large % small;
large = small;
small = rem;
}
gcd = large;
// printf("GCD(%d,%d)= %d", large, small, gcd);
}
/*if (gcd == 1) {
achilles = n;
// printf("%d\n", achilles);
}*/
printf("GCD(%d,%d)= %d", max, min, gcd);
//printf("%d\n", achilles);
}
I am trying to show the sum of the prime factors of a given number and
I'm having difficulties displaying the prime factors in my output.
Sample Output:
Input number: 6
Factors are: 1 2 3
Sum of its factor: 1 +2 +3 =6
I am able to show the sum but I want to show the 1+2+3=6 like in the sample above where the factors are 1 2 3.
Can you help me correct my syntax to achieve this? Thanks in advance.
Here's my code:
#include <stdio.h>
int main() {
int i, j, num, isPrime, sum;
printf("Input number: ");
scanf("%d", &num);
printf("Factors are: ", num);
for (i = 1; i <= num; i++) {
if (num % i == 0) {
isPrime = 1;
for (j = 2; j <= i / 2; j++) {
if (i % j == 0) {
isPrime = 0;
break;
}
}
if (isPrime == 1) {
printf("%d ", i);
sum += i;
}
}
}
printf("\nSum of its factor : %d", sum);
return 0;
}
Your code actually has undefined behavior because sum is not initialized to 0. It produces the correct sum only by chance.
You can store the factors in an array, or even construct the expression as you go with sprintf. The maximum length of the expression is not very large as there can be at most 9 different prime factors (29!! > 232)
Here is a modified version:
#include <stdio.h>
int main() {
char expr[9 * 11 + 1];
int i, j, pos, num, isPrime, sum;
printf("Input number: ");
if (scanf("%d", &num) != 1)
return 1;
printf("Factors are: 1"); // always include 1
pos = 0;
expr[pos] = '\0';
sum = 1;
for (i = 2; i <= num; i++) {
if (num % i == 0) {
isPrime = 1;
for (j = 2; j * j <= i; j++) {
if (i % j == 0) {
isPrime = 0;
break;
}
}
if (isPrime == 1) {
pos += sprintf(expr + pos, "+%d", i);
printf(" %d", i);
sum += i;
}
}
}
printf("\nSum of its factors: 1%s = %d\n", expr, sum);
return 0;
}
Output:
Input number: 6
Factors are: 1 2 3
Sum of its factors: 1+2+3 = 6
Here is a more robust and much faster version that does not have undefined behavior for very large values of num:
#include <stdio.h>
int main() {
char expr[9 * 11 + 1];
int i, pos, num;
unsigned sum;
printf("Input number: ");
if (scanf("%i", &num) != 1)
return 1;
printf("Factors are: 1"); // always include 1
pos = 0;
expr[pos] = '\0';
sum = 1;
for (i = 2; num / i >= i; i++) {
if (num % i == 0) {
pos += sprintf(expr + pos, "+%d", i);
printf(" %d", i);
sum += i;
do { num /= i; } while (num % i == 0);
}
}
if (num != 1) {
pos += sprintf(expr + pos, "+%d", num);
printf(" %d", num);
sum += num;
}
printf("\nSum of its factors: 1%s = %u\n", expr, sum);
return 0;
}
Test:
Input number: 0x7fffffff
Factors are: 1 2147483647
Sum of its factors: 1+2147483647 = 2147483648
Since you want to print all the prime factors twice, you should do that in a way so that you can avoid duplicated code. Here is an idea:
#include <stdio.h>
/* Return the smallest prime that is smaller than or equal to n */
/* Assumes that the argument is greater than 1 */
int getFirst(int n)
{
int i;
for(i = 2; i <= n; i++)
if(n % i == 0)
return i;
}
int main()
{
int num, x, tmp, sum=0;
scanf("%d", &num);
tmp = num;
printf("Factors are: ");
while(1) {
x = getFirst(tmp);
printf("%d ", x);
if (x == tmp) /* If we are at the last prime */
break;
tmp /= x;
}
printf("\n");
printf("Sum of factors is: ");
tmp = num;
while(1) {
x = getFirst(tmp);
printf("%d ", x);
sum += x;
if(x == tmp) /* If we are at the last prime */
break;
printf("+ ");
tmp /= x;
}
printf("= %d\n", sum);
}
But as has been pointed out in the comments. 1 is not a prime, and that's why I excluded it.
This program uses an array and three functions to read inputs, sum up the ones and tens place of inputted integers, and compute the average of input integers. Why can't I get more than one input that is a positive integer? The program runs after one input that is within the limits of integers that are valid.
#include <stdio.h>
int read_data(int Ar[]);
void comp_sums(int Ar[], int size); // prototypes
double comp_avg(int Ar[], int size);
int main()
{
int Ar[100];
int size;
double avg;
size = read_data(Ar);
comp_sums(Ar, size);
avg = comp_avg(Ar, size);
printf("The average of the integers in the array: %lf\n", avg);
}
int read_data(int Ar[]) // reads inputted integers, stores in array
{
int flag;
char ch;
int i,j, num;
flag = 1;
i = 0;
while (flag == 1) {
printf("Please enter an integer:\n");
j = scanf("%d", &num);
if (j != 1) {
break;
}
if (num < 0) {
continue;
} else if (num >= 100) {
flag = 0;
} else {
Ar[i] = num;
i++;
}
return i;
}
}
void comp_sums(int Ar[], int size) /* computes sum of ones and tens place of the inputted integers into the array*/
{
int i, j;
int sum_ones, sum_tens;
sum_ones = 0;
sum_tens = 0;
for (i = 0; i < size; i++) {
sum_ones += Ar[i] % 10;
j = Ar[i] / 10;
sum_tens += j % 10;
}
printf("The sum of the ones is: %d\n", sum_ones);
printf("The sum of the tens is: %d\n", sum_tens);
}
double comp_avg(int Ar[], int size) // computes average of integers
{
int i, sum;
double avg;
sum = 0;
for (i = 0; i < size; i++) {
sum += Ar[i];
}
avg = (double)size / sum;
return avg;
}
When you take an array as an argument, you have to take the length as well,
because you have to check if you are reading/writing out of bounds. Forget for a
second that the return is at that incorrect position, the user can input more
values than the array can hold and you are doing nothing to prevent the buffer overflow.
So to fix your read_data function:
int read_data(int Ar[], size_t len)
{
if(Ar == NULL || len == 0)
return 0;
int i = 0, j, num;
// imortant to check the bounds
while (i < len) {
printf("Please enter an integer:\n");
j = scanf("%d", &num);
if (j != 1) {
break;
}
if (num < 0) {
continue;
} else if (num >= 100) {
break;
} else {
Ar[i] = num;
i++;
}
}
return i;
}
I removed the flag bit because if num >=100, you would be ending the loop
anyway, so it's much simpler to do a break. Also the intention is more clearer.
Now you can call it:
int main()
{
int Ar[100];
int size;
double avg;
size = read_data(Ar, sizeof Ar / sizeof *Ar);
...
}
The problem is that you call return inside the whileloop. So as soon as you get a valid number, you'll return from the function.
Move it outside the loop. Like:
while (flag == 1) {
printf("Please enter an integer:\n");
j = scanf("%d", &num);
if (j != 1) {
break;
}
if (num < 0) {
continue;
} else if (num >= 100) {
flag = 0;
} else {
Ar[i] = num;
i++;
}
// return i; Incorrect
}
return i; // Correct