An abundant number is a natural number that is less than the sum of its proper divisors. For example 12 < 1+2+3+4+6=16 so 12 is an abundant number, while 16 > 1+2+4+8=15 is not an abundant number.
I have to write a program in C language so that for the input k, the output are all abundant numbers less than or equal to k.
I'm only a beginner at this so what I first wanted to do is to write a program that will check whether k is abundant or not. So this is what I did:
#include <stdio.h>
int main(void) {
int k, i, s = 0;
scanf("%d", &k);
for (i = 1; i < k; i++) {
if (k % i == 0)
s = s + i;
}
if (k < s)
printf("%d" is an abundant number", k);
return 0;
}
Feel free to ignore this above, I only wanted to show you I actually tried something by myself. Now I wasn't sure how to make this program list the abundant numbers that are also less than k, but I found the solution which I don't understand:
#include <stdio.h>
int main(void) {
int k, i, j, s;
scanf("%d", &k);
for (i = 1; i <= k; i++) {
s = 0;
for (j = 1; j < i; j++) {
if (i % j == 0)
s = s + j:
}
if (i < s)
printf("%d"\n", i);
}
return 0;
}
I'm confused by this nested for loop, can someone explain exactly how it works? For instance if we put k=18, what exactly happens with this for loops so that in the end we get 12 and 18 as output?
I think the best way is to step through the code manually and write down the line number of the executing code and how the variables change.
Like
L01: int k,i,j,s; // k=?, i=?, j=?, s=?
L02: scanf("%d", &k); // k=18, i=?, j=?, s=?
L03: for(i=1; // k=18, i=1, j=?, s=?
L03: i<=k; // TRUE
L04: s=0; // k=18, i=1, j=?, s=0
L05: for(j=1; // k=18, i=1, j=1, s=0
L05: j<i; // FALSE
L03: i++) // k=18, i=2, j=1, s=0
L03: i<=k; // TRUE
L04: s=0; // k=18, i=2, j=1, s=0
L05: for(j=1; // k=18, i=2, j=1, s=0
L05: j<i; // TRUE
L06: if(i%j==0) // TRUE
L07: s=s+j: // k=18, i=2, j=1, s=1
L05: j++) // k=18, i=2, j=2, s=0
L05: j<i; // FALSE
and so on ....
I takes quite some time but you should soon see the pattern and there by understand how for-loops works.
Another thing that might help you understanding for-loops are to realize that
for(i=0; i<N; i++)
{
code...
}
is equivalent to
i=0;
while (i<N)
{
code...
i++;
}
BTW:
Always check the return value from scanf - like:
if (scanf("%d", &k) != 1)
{
printf("Input error! Program terminates.\n");
exit(1);
}
the inner loop is executed k time;
when i=1 nothing happens
when i=2 the inner loop checks if 2 is abundant or not
when i=3 the inner loop checks if 3 is abundant or not
and so on. Maybe it would be better to rewrite your code so that variable names explains its meaning.
I have written a simpler implementation. This is same as your own attempt. just that it is enough to run till k/2 instead of k-1
#include<stdio.h>
int main(void) {
int k,i,j,s;
scanf("%d", &k);
s=0;
for(i=1; i<=(k/2); i++) { //running till half of the entered value is sufficient
if(k%i == 0)
{
s+=i; //if it is a divisor add it to the sum
}
}
printf("sum is %d\n\r",s);
if(k<s)
printf("%d is abundant\n\r",k);
else
printf("%d is not abundant\n\r",k);
return 0;
}
#include<stdio.h>
int main(void) {
int upper_limit,candidate,divisor,s;
scanf("%d", &upper_limit);
for(candidate=1; candidate<=upper_limit; candidate++) {
s=0;
for(divisor=1; divisor<=(candidate/2); divisor++) {
if((candidate%divisor)==0)
s=s+divisor:
}
if(candidate<s)
printf("%d"\n", candidate);
}
return 0;
}
Related
So, the output should come out with a incrementing triangle of looped numbers (1,2,3,...) combined with a decrementing triangle of stars. Like this:
1********
12*******
123******
1234*****
12345****
123456***
1234567**
12345678*
123456789
So far I have this but just can't figure out how to decrement the stars.
#include <stdio.h>
int main()
{
int i, j;
for(i=1; i<=9; i++)
{
for (j=1; j<=i; j++)
{
printf ("%d",j);
}
int k;
for(k=8; k>0; k--) {
printf("*");
}
printf("\n");
}
}
And it prints out this:
1*******
12*******
123*******
1234*******
12345*******
123456*******
1234567*******
12345678*******
123456789*******
You have:
For k in 8 down to 0 (exclusive),
Print *.
This always prints 8 stars, but you want 9-i of them.
For k in i+1 to 9 (inclusive),
Print *.
Note that all you need to do is subtract the amount of numbers printed per line from the expected (in this case) 9 expected characters. for(k=9 - i; k>0; k--)
#include <stdio.h>
int main()
{
int i, j;
for(i=1; i<=9; i++){
for (j=1; j<=i; j++){
printf ("%d",j);
}
int k;
for(k=9 - i; k>0; k--) {
printf("*");
}
printf("\n");
}
}
Outputs:
1********
12*******
123******
1234*****
12345****
123456***
1234567**
12345678*
123456789
printf has the built in ability to print only limited portions of a string.
That comes in EXTREMELY handy for problems like this:
#include <stdio.h>
int main(void) {
int i=9;
while(i --> 0)
{
printf("%.*s%.*s\n", 9-i, "123456789", i, "********");
}
return 0;
}
Output
1********
12*******
123******
1234*****
12345****
123456***
1234567**
12345678*
123456789
IDE Link
Begin with a mutable string of 9 stars. Then, replace one character at a time as you loop 9 times (ie: once for each row of output.)
#include <stdio.h>
int main( void ) {
char stars[] = "*********";
for( int i = 1; i <= 9; i++ ) {
stars[i] = (char)(i + '0');
puts( stars );
}
return 0;
}
You need 3 loops.
The outer most loop (i) keep track of line number
First inner loop (j) will print the digits in sequence equal to number of lines
Second Inner loop (k) will print *, such that number of * printed are total lines - line number i.e. (9-i)
https://godbolt.org/z/e65def4P5
#include <stdio.h>
int main()
{
for(int i=1; i<=9; i++)
{
for (int j=1; j<=i; j++)
{
printf ("%d",j);
}
for(int k=1; k<=9-i; k++) {
printf("*");
}
printf("\n");
}
}
I was wondering where the error logic in my code was, I suspect that it lies in the failure of my loop to run through completely before printing the prime numbers, but I cannot seem to fix it. I have tried reinitializing the variable fcount to 0 each time, but the resulting "prime numbers" is incorrect. My goal for the program is to have a user input number N that I can loop from 1 to N and print all prime numbers inbetween. I would highly appreciate if someone could help point out the error in my logic, and any possible solutions, thanks.
#include <stdio.h>
int main(void) {
int i,j,n, fcount = 0;
printf("Enter number n:\n");
scanf("%d",&n);
printf("prime numbers are:\n");
for (i=1; i < n; i++)
{
for (j = i; j > 0; j--)
{
if (i%j == 0)
{
fcount++;
// at some point every number will have fcount =2
fcount = 0;
}
}
}
if (fcount == 2)
{
printf("%d\n",i);
}
return 0;
}
That's not a very efficient way to test for primes, but the method works. You have two errors, though:
For each i, the fcount must start at 0, so fcount = 0 should be the first thing in that loop.
You must test fcount == 2 for each i, not just once at the end, so move that test into the loop over i.
Some observations about your code:
These errors could have been spotted easier if you had formatted the code properly: Plese make a habit of indenting every block in curly braces so that the code's structure becomes clear.
It is better to declare the variables where they are needed. That means that fcount can be local to the loop over i. The loop variable i and j can directly be declared in the loop header.
Putting all this together:
#include <stdio.h>
int main(void)
{
int n;
printf("Enter number n:\n");
scanf("%d",&n);
// Should test for input errors ...
printf("prime numbers are:\n");
for (int i = 1; i < n; i++) {
int fcount = 0;
for (int j = i; j > 0; j--) {
if (i % j == 0) {
fcount++;
}
}
if (fcount == 2) {
printf("%d\n", i);
}
}
return 0;
}
I'm trying to finish my homework, while there is something trapped me.
Here the question:
In the range of N, output those numbers whose factors sum is equal to themselves according to the following format.
Input:
1000
output:
6 its factors are 1 2 3
28 its factors are 1 2 4 7 14
496 its factors are 1 2 4 8 16 31 62 124 248
Here my code, please tell me why can't i get the right output. Appreciate it if
you can improve it for me.
Thanks in advance.
#include<stdio.h>
#define NUM 100
int main()
{
int goal[NUM];//array for factors.
int N;
scanf("%d",&N);
getchar();
for(int p=2;p<N;p++)//1 and N are not included.
{
int j=0,sum=0;
for(int i=1;i<p; )
{
//get factors and put them into array.
while(p%i==0)
{
goal[j]=i;
sum+=goal[j];
j++;
i++;
}
}
//judge the sum of factors and p the two values are equal.
if(sum==p)
{
printf("%d its factors are ",p);
for(int i=0;i<j;i++)
{
while(i==j-1)
printf("%d \n",goal[i]);
}
}
}
return 0;
}
Making the same a little clean,
int main()
{
int N, factors_sum, factors_cnt, num, j;
scanf("%d", &N);
int *factors = malloc(sizeof(int) * N/2);
if (factors == NULL)
{
perror("malloc(2)");
return 1;
}
for (num = 2 ; num < N ; ++num)
{
factors_cnt = 0;
factors_sum = 0;
for (j = 1 ; j <= num/2 ; ++j)
if (num % j == 0)
factors_sum += (factors[factors_cnt++] = j);
if (factors_sum == num)
{
printf("%d its factors are", num);
for (j = 0 ; j < factors_cnt ; ++j)
printf(" %d", factors[j]);
printf("\n");
}
}
free(factors);
return 0;
}
Modifications retaining your code:
#include<stdio.h>
#define NUM 100
int main()
{
int goal[NUM];//array for factors.
int sum=0;
int N;
scanf("%d",&N);
//getchar(); // I donno why you need this, better to remove it
for(int p=2;p<N;p++)//1 and N are not included.
{
// sum is different for every number
// need to be set to 0 individually for every number
sum = 0;
int j=0;
for(int i=1;i<p; i++) // i++ everytime
{
//get factors and put them into array.
if (p%i==0)
// changed while to if
// while would keep executing forever
{
goal[j]=i;
sum+=goal[j];
j++;
}
}
//judge the sum of factors and p the two values are equal.
if (sum==p)
{
printf("%d its factors are ",p);
for(int i=0;i<j;i++)
{
// no need for while here
printf("%d \n",goal[i]);
}
}
}
return 0;
}
I have made modifications in your code and corrected/commented where you have made mistakes.
I was reading the book "Computer Organization and Design" by Patterson and Hennesy (5th Edition) and found this bubble sort code:
void sort (int v[], int n)
{
int i,j;
for (i=0; i<n; i+=1) {
for (j = i-1; j>=0 && v[j] > v[j+1]; j+=1) {
swap(v,j);
}
}
}
void swap (int v[], int k) {
int temp;
temp = v[k];
v[k] = v[k+1];
v[k+1] = temp;
}
I don't understand how this function would sort an array. Especially if the first element of the array is also the largest, it seems to me that the index j would go out of bounds. Running the code and printing the indices confirmed this.
This is the code I used:
#include <stdio.h>
void swap (int v[], int k) {
int temp;
temp = v[k];
v[k] = v[k+1];
v[k+1] = temp;
}
void sort (int v[], int n)
{
int i,j;
for (i=0; i<n; i+=1) {
printf("%d \n", i);
for (j = i-1; j>=0 && v[j] > v[j+1]; j+=1) {
printf("%d, %d \n", i, j);
swap(v,j);
}
}
}
int main() {
int x[3] = {5,1,2};
int N = 3;
sort(x, N);
for(int i = 0; i < 3; i++) {
printf("%d ", x[i]);
}
return 0;
}
This was the result:
/Users/mauritsdescamps/Desktop/test/cmake-build-debug/test
0
1
1, 0
1, 1
1, 2
1, 3
1, 4
2
2, 1
2, 2
2, 3
Process finished with exit code 6
Is there something I am forgetting? If not, I think there must be a mistake in the second loop condition. I have seen other implementations of the algorithm but I want to know how to get this approach to work.
I've tried this code, too. I have compiled it with GCC and somehow it worked for me (the exit status of the program was 0 and the array was sorted correctly). But I also think that their is a problem with the second loop. I would change the j+= 1 instruction into j-=1. Otherwise the second loop could end in an infinite loop. Additionally I would change the i=0 instruction in the first loop into a i=1 instruction, because it would end in an unnecessary iteration.
I've been trying for last 3 days to overcome the problem but I'm failing continuously.
I'm trying to print all prime numbers from 1 to 300 in C.(Dev C++)
below is the code
#include <stdio.h>
#include <conio.h>
main() {
// 1 - 300
register int i, j;
for (i = 1; i <= 300; i++) {
for (j = 2; j < i; j++) {
if (i % j == 0) {
break;
} else {
printf("\n%d", i);
break;
}
}
}
}
please help me in this and also help me to clear the concept.
Thanks.
You are printing the numbers too early. Print the numbers at the end of the outer loop. ie, after the inner loop.
You could do
for(i=1; i<=300; i++)
{
for(j=2; j<i; j++)
{
if(i%j == 0)
{
break;
}
}
if(j>=i)
{
printf("\n%d",i);
}
}
If at the end of inner loop, the condition j<i still holds, the loop was terminated prematurely due to the break statement being executed and hence the number is not prime.
But if that condition is false, ie, if j>=i is true, the number is prime.
You could also do this with the help of a flag variable.
And you probably don't need to use the register storage class specifier. See this post.
And there's no need of the break statements. In the program you've posted,
if(i%j == 0)
{
break;
}
else
{
printf("\n%d",i);
break;
}
is same as
if(i%j == 0)
{
break;
}
printf("\n%d",i);
or just
if(i%j != 0)
{
printf("\n%d",i);
}
For primes up to 300, the Sieve of Eratosthenes algorithm is quite good.
This should do the work for now, but I am sure that there are more efficient ways for doing this job:
int main() {
int i, j;
char is_prime; // indicator for each number if it is a prime number
printf("2\n"); // first number in the series, and the only one witch is even
for (i = 3; i<=300; i += 2) // When I jump in 2 numbers each time, I save the check of all the even numbers, that we knows ahead that they are not prime numbers.
{
is_prime = 1; // Start with an assumption that the number is prime. If we will find out that it doesn't, we will turn this value to 0.
for (j = 3; j < i; j++)
{
if(i % j == 0)
{ // If this number fully divided by this `j` value, so it is not a prime number.
is_prime = 0; // Turn this variable to indicate that this is not a prime number.
break; // This loop is for testing the current number. Now we found out that it is not a prime number, so we can end this loop.
}
} // End of the inner loop that check if the current 'i' number is a prime number.
if (is_prime) { // If we found that the current 'i' number is a prime number (if is_prime != 0)
printf("%d\n", i); // Print the 'i' number.
}
}
return 0;
}
Generating prime numbers
This is the simplest way to achieve this
for(i=2 ; i <= n ; i++)
{
for(j=2 ; j<i ;j++)
{
if(i%j == 0)
break ;
}
if(i == j )
printf("%d\n",i);
}
#include<stdio.h>
void main()
{
int n,i,fact,j;
printf("Enter the Number");
scanf("%d",&n);
printf("Prime Numbers are: \n");
for(i=1; i<=n; i++)
{
fact=0;
for(j=1; j<=n; j++)
{
if(i%j==0)
fact++;
}
if(fact==2)
printf("%d " ,i);
}
getch();
}
Try to solve it your self, putting values of i and j respectively, you'll find the errors.
1.Declare a variable int and initialize it by 0 (int a=0).
2.Then in the inner for loop in the if statement increase the value of a for each division.
If(i÷j==0)
{a=a+1;//or a++
}
3.Get out of the loop now and look if the value of the a is still 0 then i is a prime else it's not!