Prime factors of a number without using a flag variable? - c

I tried finding prime factors of a number without using a flag variable but I don't know what's the fault in the code.
#include <stdio.h>
int main(int argc, char const *argv[])
{
int num, i, j;
printf("Enter a number: ");
scanf("%d", &num);
for (i = 2; i <= num; i++)
{
if (num % i == 0)
{
for (j = 2; j <= i / 2; j++)
{
if (i % j == 0)
{
printf("%d", i);
}
}
}
}
return 0;
}

You have to print values that are factor of num and prime.
In your code you are printing factors of num, but not prime by printing i after seeing that a j that divids i exists.
Instead of that, you should check for all candidates of j and print i after seeing all js tested don't divide i.
Also you may want to add some delimiters between the factors to print.
Try this:
#include <stdio.h>
int main(int argc, char const *argv[])
{
int num, i, j;
printf("Enter a number: ");
scanf("%d", &num);
for (i = 2; i <= num; i++)
{
if (num % i == 0)
{
for (j = 2; j <= i / 2; j++)
{
if (i % j == 0)
{
break; /* stop iteration because a factor is found */
}
}
if (j > i / 2) /* check if the iteration ended not by finding factor but by checking all candidates */
{
printf("%d\n", i);
}
}
}
return 0;
}

Your approach feels a bit convoluted. Perhaps just do something like:
#include <stdio.h>
#include <stdlib.h>
int
main(int argc, char **argv)
{
unsigned num = argc > 1 ? strtoul(argv[1], NULL, 10) : 137;
int count = 0;
printf("%d = ", num);
for( unsigned i = 2; i <= num; i++ ){
while( num % i == 0 ){
printf("%s %d", count++ ? " *" : "", i);
num /= i;
}
}
printf(" ( %d factor%s )\n", count, count == 1 ? "" : "s");
return 0;
}

Related

Problem with program to list primes below integer using arrays and nested loops

#include <stdio.h>
#include <math.h>
#define MAX_SIZE 10000
int main(void)
{
int a[MAX_SIZE];
int N;
int L; /* the current size of the list */
/* read in the upper limit. Keep reading until
a valid number between 3 and the maximum that
can be handled by the array is entered */
double b[10000];
int j, i;
L = 0;
printf("Enter the upper limit:\n");
do {
scanf("%d", &N);
} while (N<3 || N>MAX_SIZE+2);
int prime;
for (j = 1; j < N; j++)
{
prime = 1;
for (i = 2; i < j; i++)
{
if (j % i == 0)
{
prime = 0;
break;
}
}
if (prime)
{
a[i] = j;
L++;
}
}
/* write out the result - DO NOT CHANGE THIS */
for(i=0;i<L;i++)
printf("%d ",a[i]);
printf("\n");
return 0;
}
Program needs to take an integer, calculate primes below that integer, print that list of primes.
I think my problem is related to the loops.
The program is calculating the primes but listing 0 if the number previously there isnt prime eg a[4] is now printing as 0
Any help is appreciated.
thanks.
Is this what you were trying to implement?
#include <stdio.h>
#define MAX_SIZE 100
int main(void)
{
int primes[MAX_SIZE];
int primes_found = 0;
int limit = 0;
while (limit < 3)
{
printf("Enter the upper limit:\n");
scanf("%d", &limit);
}
for (int candidate = 2; candidate <= limit && primes_found < MAX_SIZE; candidate++)
{
int divisor = 2;
int is_prime = 1;
while(is_prime && divisor < candidate)
is_prime = candidate % divisor++ != 0;
if (is_prime)
primes[primes_found++] = candidate;
}
for (int i = 0 ; i < primes_found ; i++)
printf("%d ", primes[i]);
printf("\n");
return 0;
}

where to put statement for powerful number?

I have make this program that calculates number factorization such as 60 = 2^2 * 5 * 3.
How can i modify my code in order to print POWERFUL NUMBERS such as 9000 = 2^3 * 3^2 * 5^3 without using math.h library and without using arrays?
Thank you very much!!
#include<stdio.h>
#define MAX 1000
int main(){
int num;
int counter;
int number;
char factorizationOutput;
int isAchiles = 0;
int factor=2;
for(counter=2;counter<=MAX;counter++){
isAchiles = 1;
number=counter;
int factor=2;
while(factor<number){
int power=0;
if(number%factor==0){
while(number%factor==0){
number=number/factor;
power++;
}
if(power == 1){
isAchiles = 0;
}
printf("%d^%d",factor,power);
if(number!=1)
printf(" X ");
}
factor++;
}
if(number!=1)
printf("%d^1.\n",factor);
if(isAchiles == 1){
printf("factorazation of number %d is: ",counter);
}
}
}
#include<stdio.h>
int main(void)
{
int n;
scanf("%d", &n);
printf("%d = ", n);
for(int i = 1; i <= n; i++)
{
int count = 0;
for(int j = 1; j <= i; j++)
{
if(i % j == 0)
{
count++;
}
}
int l = 0;
if(count == 2)
{
while(n % i == 0)
{
l++;
n = n/i;
}
printf("%d^%d*", i, l);
}
}
}

How to count number that contains 3 between 1 and N where N is the given input?

Given a number N, I wish to count the number of 3's that occur in the
the range 1 - N.
int N;
int cnt = 0;
scanf("%d", &N);
for (int i = 1; i <= N; i++) {
if (i < 30) {
if (i % 10 == 3)
cnt++;
}
else {
while (i > 0) {
if (i % 10 == 3) {
cnt++;
}
i = (i / 10);
}
}
}
printf("%d", cnt);
When my input is between 1 to 29 this program work correctly but when the input is beyond 30 the program gives me a wrong answer.
You are using the same variable for the outer for loop and the inner while loop.
You need to use a different variable for the inner while loop.
With the variable j controlling the while loop, your program will look like this:
#include <stdio.h>
int main(int argc, char * argv[])
{
int N, j;
int cnt = 0;
scanf("%d", &N);
for (int i = 1; i <= N; i++) {
if (i < 30) {
if (i % 10 == 3)
cnt++;
}
else {
j = i;
while (j > 0) {
if (j % 10 == 3) {
cnt++;
}
j = (j / 10);
}
}
}
printf("%d", cnt);
return -1;
}
Output:
>a.exe
30
4
>a.exe
33
8

C program for below pyramid If possible JAVA code also [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 7 years ago.
Improve this question
Desired Output
1234554321
1234__4321
123____321
12______21
1________1
Code
#include<stdio.h>
int main()
{
int num,c,sp,r=1;
printf("Enter loop repeat number(rows): ");
scanf("%d",&num);
printf("\n");
for(; num>=1; num--,r++)
{
for(c=1; c<=num; c++)
printf("%d",c);
for(sp=r; sp>1; sp--)
printf("_");
for(sp=r; sp>1; sp--)
printf("_");
for(c=num; c>=1; c--)
printf("%d",c);
printf("\n");
}
}
I am looking for other alternative codes which are less complex. Any help would be appreciated.
Rather than making multiple calls to printf, it seems cleaner to construct the string yourself:
#include<stdio.h>
#include<stdlib.h>
int
main( int argc, char ** argv )
{
unsigned num = argc > 1 ? strtol( argv[1], NULL, 0 ) : 5;
char digits[] = "123456789_987654321";
char *rhs = digits + sizeof digits - 1 - num;
if( num > 9 ) {
fprintf( stderr, "argument must be < 10" );
exit( EXIT_FAILURE );
}
digits[num] = '\0';
for( ; num > 0; ) {
printf( "%s%s\n", digits, rhs );
digits[ sizeof digits - 1 - num ] = '_';
digits[ --num ] = '_';
}
return 0;
}
Your lines are symmetrical. You can use a recursive function where you print before and after recursing to achieve this:
#include <stdlib.h>
#include <stdio.h>
void line(int i, int n, int m)
{
if (i < n) {
putchar(i > m ? '_' : '0' + (i + 1) % 10);
line(i + 1, n, m);
putchar(i > m ? '_' : '0' + (i + 1) % 10);
}
}
int main(int argc, char **argv)
{
int i, n = 0;
if (argc > 1) n = atoi(argv[1]);
if (n <= 0) n = 5;
i = n;
while (i--) {
line(0, n, i);
putchar('\n');
}
return 0;
}
The lines themselves are controlled with a regular loop. The newline '\n' can't be part of the recursive function, because it doesn't fit the symmetric pattern; it has to be printed explicitly. This version takes the size of the pyramid from the command line with a default of 5.
Something like this should do:
#include <stdio.h>
int main()
{
int num;
printf("Enter loop repeat number(rows): ");
scanf("%d",&num);
printf("\n");
for (int row = 0; row < num; ++row) {
int columnLimit = num - row;
for (int column = 1; column <= columnLimit; ++column) {
printf("%d", column);
}
for(int spacing = 0; spacing < row; ++spacing) {
printf("__");
}
for (int column = columnLimit; column > 0; --column) {
printf("%d", column);
}
printf("\n");
}
}
IDE One
#include<stdio.h>
int main()
{
int num,c,sp;
printf("\n");
for(num =5; num>=1; num--)
{
for(c=1; c<=5; c++)
{
if(c>num)
{
printf("_");
}
else
{
printf("%d",c);
}
}
for(c=5; c>=1; c--)
{
if(c>num)
{
printf("_");
}
else
{
printf("%d",c);
}
}
printf("\n");
}
}
Use ternary operator for simplification, this way you only need two lines
inside of the inner loop code,
val = column <= num ? column : limit - column + 1;
printf("%c", val > row ? '_' : val + 0x30);
Here it is:
int main(){
int num,column,row,limit,val;
printf("Enter loop repeat number(rows): ");
scanf("%d",&num);
printf("\n");
limit = num * 2;
for (row = num; row > 0; --row){ //num times
for (column = 1; column <= limit; ++column){
val = column <= num ? column : limit - column + 1;
printf("%c", val > row ? '_' : val + 0x30);
}
printf("\n");
}
return 0;
}
The downside is you still have to call printf multiple times. But obviously the code is really compact!
A revisited one that asks the user for the max number...
int main()
{
int num;
printf("Enter loop repeat number(rows, 9 max): ");
scanf("%d",&num);
if (num > 9) num = 9;
int i,j;
for (i=num ; i>0 ; i--) {
for(j=1 ; j<=num ; j++) {
printf("%c", j>i ? '_':0x30+j);
}
for(j=num ; j>=1 ; j--) {
printf("%c", j>i ? '_':0x30+j);
}
printf("\n");
}
return 0;
}
0x30 is the ascii code for 0, adding j gives 1 to num.
edit a recursive bonus ...
int num; // global to avoid putting it in the recursive function
void recursive(int i, int j) {
printf("%c", i>j ? '_':0x30+i);
if (i<num) recursive(i+1, j);
printf("%c", i>j ? '_':0x30+i);
if(i==1) {
printf("\n");
if (--j > 0) recursive(1, j);
}
}
To be called as recursive(1, num);
int main(int argc, char **argv)
{
printf("Enter loop repeat number(rows, 9 max): ");
scanf("%d",&num);
if (num > 9) num = 9;
recursive(1, num);
return 0;
}
Assuming (but not checking!) that input does not exceed 9:
#include<stdio.h>
int main()
{
int num, r, c;
printf("Enter loop repeat number(rows): ");
scanf("%d",&num);
printf("\n");
for(r=num; r>=1; row--)
{
for(c=1; c<=num; c++)
putc(c<=r ? ('0'+c) : '_');
for(c=num; c>=1; c--)
putc(c<=r ? ('0'+c) : '_');
putc("\n");
}
}
The question seems to assume that it won't go above an input of 9, so I'll assume the same ...
int num=5; // Set as required
int max=9;
char leftNums[10] = "123456789";
char rightNums[10] = "987654321";
char pyramid[17] = "________________";
int rightStart = max - num;
for (int row=0; row<num; row++) {
int colLimit = num - row;
printf("%*.*s", colLimit, colLimit, leftNums);
printf("%*.*s", 2*row, 2*row, pyramid);
printf("%*.*s\n", colLimit, colLimit, &rightNums[rightStart+row]);
// Or, if you prefer for the last line:
// printf("%*.*s\n", colLimit, colLimit, rightNums+rightStart+row);
}
Notes:
You can obviously easily play around with letters, numbers and so on in this approach.
If you want to go above 9, you'll probably want to use letters rather than numbers ...
IDEone.com
This works until 9 rows:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
int num, cols;
int i, j;
printf("Enter loop repeat number(rows): ");
scanf("%d",&num);
printf("\n");
if (num<10)
{
cols=num*2;
char **matrix = malloc(num*sizeof(char *));
for(i=0; i<num; i++)
{
matrix[i] = malloc(cols*sizeof(char *));
memset(matrix[i], '_', cols);
for (j=0; j<num; j++)
{
if (j<(num-i))
{
matrix[i][j] = (j+1)+0x30;
matrix[i][cols-j-1] = matrix[i][j];
}
}
}
for (i=0; i<num; i++)
{
for (j=0; j<cols; j++)
printf("%c", matrix[i][j]);
printf("\n");
free(matrix[i]);
}
free(matrix);
}
else
{
printf("Max allowed rows = 9\n");
}
return 0;
}
IDE One

Printing prime numbers up to n

I have written some code to ask the user for n, then print the prime numbers up to n. However when I use it, i.e with 10, it only prints the non-prime numbers
/* Asks for the amount of prime numbers you would like to print, then prints them */
#include <stdio.h>
int main(void)
{
int n, i, j, check;
printf("How many prime numbers would you like to print? ");
scanf("%d", &n);
for (i = 2; i <= n; i++) {
check = 0;
for (j = 2; j < i ; j++) {
if (i % j == 0) {
check = 1;
if (check == 1) {
printf("%d\n", i);
}
}
}
}
return 0;
}
How many prime numbers would you like to print? 10
4
6
6
8
8
9
10
10
I've tried everything but I think I am missing something really trivial!
This is how it should be:
for (i = 2; i <= n; i++)
{
check = 0;
for (j = 2; j < i ; j++)
{
if (i % j == 0)
{
check = 1;
break;
}
}
if (check == 0)
{
printf("%d\n", i);
}
}
Also, in the inner loop you don't have to divide the number till j < i. You don't have to go beyond i/2.
As Weather Vane said, the mod operator % returns 0 if i is exactly divisible by j and if this is true then the number is not prime. Your conditional statement is backwards.
#include <stdio.h>
int main(void)
{
int n, i, j, check;
printf("How many prime numbers would you like to print? ");
scanf("%d", &n);
for (i = 2; i <= n; i++)
{
check = 0;
for (j = 2; j < i ; j++)
{
if (i % j == 0)
{
check = 1;
break;
}
}
if (check == 0)
{
printf("%d\n", i);
}
}
return 0;
}
How many prime numbers would you like to print? 10
2
3
5
7
Several problems.
First, when you set check = 1, that means that i divides evenly, so n is not prime, so you shouldn't print it. You should be printing the number when check == 0.
Second, you're printing each time through the inner loop. You should test check at the end of the loop, to ensure that none of the numbers divided it.
As an improvement, there's no need to keep checking once you find one number that divides evenly. So you can break out of the inner loop as soon as you set check = 1.
#include <stdio.h>
int main(void)
{
int n, i, j, check;
printf("How many prime numbers would you like to print? ");
scanf("%d", &n);
for (i = 2; i <= n; i++) {
check = 0;
for (j = 2; j < i ; j++) {
if (i % j == 0) {
check = 1;
break;
}
}
if (check == 0) {
printf("%d\n", i);
}
}
return 0;
}
try looking at this code
#include <stdio.h>
int IsPrime(int num)
{
int i = 2;
for (i = 2; i < num; i++) if (num % i == 0) return 0;
return 1;
}
int main(void)
{
int n, i;
char *nStr = (char*)malloc(10);
printf("How many prime numbers would you like to print? ");
fgets(nStr, 9, stdin);
n = atoi(nStr);
for (i = 1; i <= n; i++) if (IsPrime(i)) printf("%d\n", i);
getchar();
return 0;
}
and about your code, you should print the number only if check remains 0.

Resources