#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.
Related
What I want to do is to get a cumulative sum of previous integers starting from 1, for example:
If my input is 4, then the function should work in this way;
1 + (1+2) + (1+2+3) + (1+2+3+4) = 20.
And the output needs to be 20. Also, I have to get this done by a function, not in main(); function while using int n as the only variable.
What I've tried is to make a function which adds from 1 to integer N, and use 'for'to make N start from 1, so that it can fully add the whole numbers until it reaches N.
#include <stdio.h>
int sum(int n);
int main() {
int n, input, sum;
sum = 0;
scanf("%d", &n);
for (n = 0; n <= input; n++) {
sum += n;
}
printf("%d", sum);
return 0;
}
int sum(int n) {
int i, n, sum = 0;
scanf("%d", &n);
for (i = 1; i <= n; i += 1){
sum += i;
}
return n;
}
What I expected when the input is 4 is 20, but the actual output is 10.
I would have written it this way, remarks are where changes been made
#include <stdio.h>
int sum(int n);
int main() {
int n, input, sum;
// sum = 0; // no need for this
scanf("%d", &n);
/* the next for has no use
for (n = 0; n <= input; n++) {
sum += n;
} */
// I would be adding some input sanitazing if possible here
printf("%d", sum(n));
return 0;
}
int sum(int n) {
int i, /*n, */ rsum = 0; // n is already a parameter, rsum for running sum
// scanf("%d", &n); // nope nope, scanf and printf should be avoided in functions
for (i = 1; i <= n; i++){ // changed i +=1 with i++ , easier to read
for (j=1;j<=i;j++) // need this other loop inside
rsum += j;
}
return rsum;
}
Here it is with a single loop; very fast.
#include <stdio.h>
int cumulative_sum(int m)
{
int sum = 0;
for(int n=1; n<=m; ++n) sum += n*(n+1);
return sum/2;
}
int main(void)
{
int n;
printf("Input value N: ");
scanf("%d", &n);
printf("Answer is %d\n", cumulative_sum(n));
return 0;
}
The main issue is in the function, you are doing only 1 loop (you have also some logical things, which compiler should tell you, like same naming of variable and function.. eg.),
so in case you will put 4 as the input, loop will do only 1+2+3+4, but your case if different, you want to make suma of all iterations like 1 + (1+2) + (1+2+3) + (1+2+3+4)
you are doing only last step basically (1+2+3+4), 4 iterations (4x suma), but actually you need 10 iterations (due suma of all particular suma of elements)
As suggested, try to debug your code - What is a debugger and how can it help me diagnose problems?
- it will really help you do understand your code
As mentioned, the issue is in
int sum(int n) {
int i, n, sum = 0;
scanf("%d", &n);
for (i = 1; i <= n; i += 1){
sum += i;
}
return n;
}
You have to make two loops eg. like follows:
int sum,n = 0;
//scanf("%d", &n);
n = 4; //input simulation
//just for demonstration
int iterations = 0;
//counter for total loops (how many "brackets" needs to be count)
for(int loopsCounter = 1; loopsCounter <= n;loopsCounter++){
//counter for child elements in brackets (like 1+2 ,1+2+3, ..)
for (int sumaLoopCounter = 1; sumaLoopCounter <= loopsCounter; sumaLoopCounter++){
//simply make sum with the given number
/* first step 0 +1
second 1+2 added to previous suma = 1+3
third 1+2+3,.. added to previous = 4+6
...
*/
sum += sumaLoopCounter;
//just testing for demonstration
iterations++; //iterations = iterations + 1
}
}
printf("%i \n",iterations);
printf("%i",sum);
Then you got output as expected - sum of all "bracket elements" and 10 iterations, which matches numbers of needed additions
10
20
Goldbach's conjecture states that every even integer over 4 is the sum of two primes, I am writing a program in C to find these pairs. To do this it first finds all the primes less than a user given number. I have a for loop to iterate from 4 to the user given number and find the pairs within the loop body. When that loop gets to about around 40, suddenly jumps back down by about 30 and then continues to iterate up (with user input 50 it jumped from 38 to 9, with input 60 it jumped from 42 to 7). I can't figure out why this is happening. Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <sys/types.h>
#include <unistd.h>
struct pair{
int a;
int b;
}pair_t;
int main(){
int N;
int numPrimes = 1;
int *primes = malloc(100*sizeof(int));
int isPrime = 1;
primes[0] = 2;
int timesRealloc = 0;
int availableSlots = 100;
printf("Please enter the largest even number you want to find the Goldbach pair for: \n");
scanf("%d", &N);
struct pair pairs[N/2 + 4];
int j = 0;
int i;
for (i = 3; i <= N; i+=2){
j = 0;
isPrime = 1;
while (primes[j] <= sqrt(i)) {
if (i%primes[j] == 0) {
isPrime = 0;
break;
}
j++;
}
if (isPrime == 1){
primes[numPrimes] = i;
numPrimes++;
}
if (availableSlots == numPrimes){
timesRealloc++;
availableSlots += 100;
primes = realloc(primes, availableSlots*sizeof(int));
}
}
printf("The largest prime I found was %d\n", primes[(numPrimes-1)]);
int k;
for (i=4; i<=N; i+=2){
printf("i is %d, N is %d\n", i, N);
if (i > N){ break; }
for (j=0; j<numPrimes; j++){
for (k=0; k<numPrimes; k++){
int sum = primes[j] + primes[k];
if(sum == i){
pairs[i].a = primes[j];
pairs[i].b = primes[k];
}
}
}
}
for (i=4; i<=N; i+=2){
printf("%d is the sum of %d and %d\n", i, pairs[i].a, pairs[i].b);
}
return 0;
}
You attempt to be space efficient by compressing the pairs array to just hold every other (even) number and start from 4 instead of zero. However, you miscalculate its size and then when you go to use it, you treat it like it hasn't been compressed and that there's a slot for every natural number.
The code suffers from having the prime array calculation in main() along with the other code, this is best separated out. And when it looks for pairs, it doesn't quit when it finds one, nor when it starts getting sums greater than the target. My rework below attempts to address all of these issues:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <stdbool.h>
#define INITIAL_SLOTS (100)
struct pair {
int a;
int b;
} pair_t;
int compute_primes(int limit, unsigned **primes, int size) {
int numPrimes = 0;
(*primes)[numPrimes++] = 2;
for (int i = 3; i <= limit; i += 2) {
bool isPrime = true;
for (int j = 0; (*primes)[j] <= i / (*primes)[j]; j++) {
if (i % (*primes)[j] == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
(*primes)[numPrimes++] = i;
}
if (numPrimes == size) {
size *= 2;
*primes = realloc(*primes, size * sizeof(unsigned));
}
}
return numPrimes;
}
int main() {
int N;
printf("Please enter the largest even number you want to find the Goldbach pair for: \n");
scanf("%d", &N);
unsigned *primes = calloc(INITIAL_SLOTS, sizeof(unsigned));
int numPrimes = compute_primes(N, &primes, INITIAL_SLOTS);
printf("The largest prime I found was %d\n", primes[numPrimes - 1]);
struct pair pairs[(N - 4) / 2 + 1]; // compressed data structure
for (int i = 4; i <= N; i += 2) {
int offset = (i - 4) / 2; // compressed index
bool found = false;
for (int j = 0; ! found && j < numPrimes; j++) {
for (int k = 0; ! found && k < numPrimes; k++) {
int sum = primes[j] + primes[k];
if (sum == i) {
pairs[offset].a = primes[j];
pairs[offset].b = primes[k];
found = true;
} else if (sum > i) {
break;
}
}
}
}
for (int i = 4; i <= N; i += 2) {
int offset = (i - 4) / 2; // compressed index
printf("%d is the sum of %d and %d\n", i, pairs[offset].a, pairs[offset].b);
}
free(primes);
return 0;
}
OUTPUT
> ./a.out
Please enter the largest even number you want to find the Goldbach pair for:
10000
The largest prime I found was 9973
4 is the sum of 2 and 2
6 is the sum of 3 and 3
8 is the sum of 3 and 5
10 is the sum of 3 and 7
12 is the sum of 5 and 7
14 is the sum of 3 and 11
...
9990 is the sum of 17 and 9973
9992 is the sum of 19 and 9973
9994 is the sum of 53 and 9941
9996 is the sum of 23 and 9973
9998 is the sum of 31 and 9967
10000 is the sum of 59 and 9941
>
I'm just trying to add all common factors of 3 and 5, stopping at a sum of 1000. I keep getting an expected expression on line 15:18. Is there anyone that can find any new errors or help? It would be much appreciated. Thanks.
#include<stdio.h>
#include<stdlib.h>
/*Multiples of 3 and 5
If we list all natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6
and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.*/
int cd_function(int n, int sum)
{
if(sum >= 1000)
return 0;
if(n%3 == 0 || n%5 == 0)
sum + return cd_function(n, sum);
}
int main(void)
{
int i, iter, sum = 0;
for(i = 0; i < cd_function(iter, sum); i++)
sum++;
return 0;
}
#include<stdio.h>
#include<stdlib.h>
Most people will add a space here:
#include <stdio.h>
#include <stdlib.h>
.
int cd_function(int n, int sum)
{
if(sum >= 1000)
return 0;
if(n%3 == 0 || n%5 == 0)
sum + return cd_function(n, sum);
}
There is two ways, to have this functions add n to sum: Either by passing sum as pointer (reference), this would be done this way:
void cd_function(int n, int * sum) {
// if (*sum >= 1000) - no need to test this here
if (!n%3 || !n%5) {
*sum += stuff;
}
}
or by having the function return the new sum:
int cd_function(int n, int sum) {
// if (sum >= 1000) - no need to test this here
if (!n%3 || !n%5) {
return sum + stuff;
} else {
return sum;
}
}
Now, sum + return cd_function(n, sum); is wrong, YSC already told so in his comment. So you should either use *sum += n; or return sum + n; (i.e. replace stuff by n above).
int main(void)
{
int i, iter, sum = 0;
Since you don't need iter, get rid of it:
int i, sum = 0;
for(i = 0; i < cd_function(iter, sum); i++)
sum++;
a. If you want to sum some[tm] is, then you shouldn't increment sum in each iteration.
for (i = 0; i < cd_function(iter, sum); i++)
;
b. Then you should get a proper exit condition. You wanted to sum everything until you reach a sum >= 1000, so write that in the condition:
for (i = 0; sum < 1000; i++)
/* ??? i < cd_function(iter, sum) */;
c. Depending on the implementation of cd_function you choose from above, you would now either call
cd_function(i, &sum);
or
sum = cd_function(i, sum);
d. And finally, you should add curly brackets, even there is only one statement:
for (i = 0; sum < 1000; i++) {
// option 1
cd_function(i, &sum);
// option 2
sum = cd_function(i, sum);
}
rest is fine:
return 0;
}
I have this assignment for my intro to C programming class and part of my code has to find the sequence of the sum of square digits of a number in order to determine after if the given number is a happy number (sum of square digits = 1)
Here's part of my code:
#include <stdio.h>
#include <math.h>
// The sum of square digits function
int sqd (int x) {
int sum = 0;
while (x > 0) {
sum = sum + pow(x%10, 2);
x = x/10;
}
return sum;
}
// The search function
int search (int a[], int val, int size) {
int i;
for (i = 0; i < size; i++) {
if (a[i] == val) {
return 1;
}
}
return 0;
}
// The main program
void main () {
int a [1000] = {0};
int N;
int count = 1;
int j;
printf("Please enter the potential happy number:\n", N);
scanf ("%d", &N);
a[0] = N;
a[count] = sqd (N);
do {
a[count] = sqd (a[count-1]);
count++;
} while (search (a, a[count], count));
for ( j = 0; j <= count; j++) {
printf("%d\n", a[j]);
}
}
It only prints the first three sums in the sequence. I really don't know how to make it work.
Thank you in advance
This line
while (search (a, a[count], count));
makes sure that you break out of the loop after one round since a[1] is not equal toa[0]. You can change that line to be:
while (a[count-1] != 1);
You also need to add a clause to make sure that you stop when the limit of the array is reached. Update that line to be:
while (a[count-1] != 1 && count < 1000 );
And then, change the printing loop to use i < count, not i <= count. Using <= will result in accessing the array out of bounds when the user enters a sad number.
for ( j = 0; j < count; j++){
printf("%d\n", a[j]);
}
Update
After a bit of reading on happy numbers at Wikipedia, I understand why you had call to search in the conditional of the while. The following also works.
} while ( ! (a[count-1] == 1 || search(a, a[count-1], count-1)) );
That will search for the last number in the array but only up to the previous index.
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;
}