How to print All zeros in C? - c

I want to print all the zeros in the input using this code.
for example:
input: 10000 -------------- output: 0000
but I get this:
input: 10000 -------------- output: 0
this is the source code in C99:
#include<stdio.h>
int main() {
int co = 0, inputNumber, i, j, prod = 1, number = 0, ten = 10, newValue;
int numberOfInputs;
scanf("%d", &numberOfInputs);
for(i = 1; i <= numberOfInputs; i++) {
scanf("%d", &inputNumber);
for(j = 1; j < inputNumber; j++) {
if(inputNumber % j == 0) {
prod = prod * j;
}
}
if(prod < 10000)
printf("%d", prod);
else {
newValue = prod;
while((int)prod / 10 != 0) {
prod = (int) prod/10;
co++;
number = newValue % ten;
ten *= 10;
if(co == 4) {
printf("%d \n", number);
break;
}
}
}
}
return 0;
}
Please some help guys :)

So basically, you want to print out the four lowest-order digits of the product with leading zeros, which is pretty simple:
printf( "%04d\n", prod % 10000 );
Cleaning up and reformatting your code a bit basically reduces to this:
#include <stdio.h>
int main( void )
{
int inputNumber, i, j, prod=1;
int numberOfInputs;
scanf( "%d", &numberOfInputs );
for(i = 1; i <= numberOfInputs; i++ )
{
scanf("%d", &inputNumber);
for(j = 1; j < inputNumber; j++ )
{
if( inputNumber % j == 0)
{
prod = prod*j;
}
}
printf( "%04d\n", prod % 10000 );
}
return 0;
}

Using a completely different approach, you can do this:
#include<stdio.h>
int main(){
int zeroCounter=0;
char inputNumber[256];
printf("Please enter the numerical value:");
fgets(inputNumber,256, stdin);
int j;
for(j=0; inputNumber[j]!='\n'; j++)
{
if(inputNumber[j]=='0') zeroCounter++;
}
printf("this value had %d zeros, here they are: ",zeroCounter);
while(zeroCounter!=0)
{
printf("0");
zeroCounter--;
}
printf("\n");
return 0;
}
what this code does is it sniffs the character array you input, and counts the 0 characters. then it can print them if required. no division and bitshifting shenanigans required.

Well your current problems are that because of the overflows, prod ends to be 0. And as 0 < 10000 you just pass through the single print: if(prod<10000)printf("%d",prod); just bypassing all your complex printing code.
In fact it overflows (to a negative value) at least at for a value as small as 84.
But that's not all. Even if prod does not overflow, you compute a number of at most 4 digits in number but print if in %d format. If number is less than 1000, you will not print the highest order 0 with that format, but you should use %04d.
Here is a minimally fixed version:
int main(){
int co=0,inputNumber,i,j,prod=1,number=0,ten=10,newValue;
int numberOfInputs;
scanf("%d",&numberOfInputs);
for(i=1;i<=numberOfInputs;i++)
{
scanf("%d",&inputNumber);
prod = 1; /* reset prod */
for(j=1;j<inputNumber;j++) {
if(inputNumber%j==0) {
prod = prod*j;
if (prod <= 0) {
break;
}
}
}
if (prod <=0) {
printf("Overflow\n");
}
else if(prod<10000) {
printf("%04d\n",prod);
}
else
{
newValue = prod;
while((int)prod/10 != 0)
{
prod = (int)prod/10;
co++;
number = newValue%ten;
ten*=10;
if(co==4)
{
printf("%04d \n",number);
break;
}
}
}
}
return 0;
}
But in fact the else part should just be:
else
{
printf("%04d \n",prod % 10000);
}

Related

I want to print the following pyramid of number pattern

1
2 4
3 5 7
6 8 10 12
9 11 13 15 17
Following is the code in which I am not able to print the pyramid:-
int main()
{
int i,j;
for(i=1;i<=5;i++){
for(j=1;j<=i;j++){
printf("%d ",i*j);
}
printf("\n");
}
return 0;
}
You need to track both even and odd numbers .
#include <stdio.h>
int main()
{
int even=1,odd=2;
int n=10;
for (int i = 1; i <= n; i++)
{
int a= (i % 2 == 0);
for (int j = 1; j < i; j++)
{
if(a)
{
printf("%d ",even);
}
else
{
printf("%d ",odd);
}
even += a ? 2 : 0;
odd += a ? 0 : 2;
}
printf("\n");
}
return 0;
}
Not very clean and compact algorithm but sth like this would work:
#include <stdio.h>
#include <stdlib.h>
int main() {
char tmp[10];
int n = 0, row = 1, odd = 1, even = 2, c = 0, selectOdd, fin = 0;
printf("maximum number: ");
scanf("%s", tmp);
n = atoi(tmp);
if (n != 0) {
while (fin < 2) {
selectOdd = row % 2;
c = row;
if (selectOdd) {
while (c != 0) {
printf("%3d", odd);
odd += 2;
if (odd > n) {
fin++;
break;
}
c--;
}
}
else {
while (c != 0) {
printf("%3d", even);
even += 2;
if (even > n) {
fin++;
break;
}
c--;
}
}
printf("\n");
row++;
}
}
return 0;
}
it's simple
your algorithm is odd, even, odd,... and so on
so you start with odd number until reach line number
for next line is even and you can find start number with this
you just need find number at start of line and continue print number number
in each step you just need
num += 2;
remember 'lineIndex' start from 1
num = (lineIndex - 1) * 2 + lineIndex % 2;
this is a full code
#include <stdio.h>
int main(){
int numIndex;
int lineIndex;
int num;
for (lineIndex = 1; lineIndex <= 5; lineIndex++) {
num = (lineIndex - 1) * 2 + lineIndex % 2;
for (numIndex = 0; numIndex < lineIndex; numIndex++) {
printf("%2d ", num);
num += 2;
}
printf("\n");
}
}

Problems with printing output C

So I have to write a code for school. I did, but my outputs are not the way they asked for. This code gives me prime number between 2 different numbers. So i have to print those numbers in rows. But yeah there are getting zeros between the answers below you can see what I mean. How can I fix this?
#include <stdio.h>
int is_prime (int number)
{
int is_prime= 1, i;
if (number < 2)
{
is_prime = 0;
}
else
{
for(i = 2; (i * i) <= number; i++)
{
if ((number % i) == 0)
{
is_prime = 0;
break;
}
else
{
is_prime = 1;
}
}
}
return is_prime;
}
int main (void)
{
int lower_limit, upper_limit, i;
scanf("%d\n%d", &lower_limit, &upper_limit);
for(i = lower_limit; i <= upper_limit; i++)
{
if (is_prime (i))
{
printf("\n%d", i);
}
else
{
printf("\n%d", is_prime(i));
}
}
return 0;
}
Output
0
11
0
13
0
0
0
17
0
19
0
Reference
11
13
17
19
It's in this if block:
if (is_prime (i))
{
printf("\n%d", i);
}
else
{
printf("\n%d", is_prime(i));
}
What this says is "if the number is prime print it, otherwise print whether it is prime (which at this point you've established it's not)".
Just get rid of the else block.
If the number is prime number just print it. No else needed - even worse it is incorrect.
You can simplyfy the the is_prime function
int is_prime (int number)
{
int is_prime = number > 1, i;
for(i = 2; (i * i) <= number; i++)
{
if ((number % i) == 0)
{
is_prime = 0;
break;
}
}
return is_prime;
}
int main (void)
{
int lower_limit, upper_limit, i;
scanf("%d\n%d", &lower_limit, &upper_limit);
for(i = lower_limit; i <= upper_limit; i++)
{
if (is_prime (i))
{
printf("\n%d", i);
}
}
return 0;
}
https://godbolt.org/z/4d8qhx
Another problem: overflow.
Avoid int overflow in i*i, which is undeifned behavior (UB).
This can happen when number is a prime near INT_MAX.
// for(i = 2; (i * i) <= number; i++)
for(i = 2; i <= number/i; i++)
A good compiler will see the nearby number%i and number/i and emit efficient code for the two of them, thus not incurring an expensive 2nd operation.
The below also overflows when upper_limit == INT_MAX
for(i = lower_limit; i <= upper_limit; i++)
Perhaps
for(i = lower_limit; i - 1 < upper_limit; i++)
OK as long as lower_limit > INT_MIN.

How many prime numbers C program

I wrote this program to find prime numbers between 1 and 50000, and I still need to find how many prime numbers there is (I tried a lot of tricks but I did not succeed)
#include <stdio.h>
//int getValueFromUser();
void PrintListOfPrime(int value);
int main() {
int value = 23;
PrintListOfPrime(value);
return 0;
}
void PrintListOfPrime(int value) {
int ValueIsPrime; //ValueIsPrime is used as flag variable
printf("The list of primes: ");
for (int i = 2; i <= value; i++) {
ValueIsPrime = 1;
/* Check if the current number i is prime or not */
for (int j = 2; j <= i / 2; j++) {
/*
* If the number is divisible by any number
* other than 1 and self then it is not prime
*/
if (i % j == 0) {
ValueIsPrime = 0;
break;
}
}
/* If the number is prime then print */
if (ValueIsPrime == 1)
printf("%d, ", i);
}
printf("\n");
}
I tried a lot of tricks but I did not succeed
If OP's code takes too long to ran, iterate to the square root of i, not up to i/2.
j <= i / 2 is very slow. Use j <= i / j instead.
Form a count and increment with every prime. #gspr
if (ValueIsPrime == 1) {
printf("%d, ", i);
prime_count++;
}
Bigger change yet even faster to "find prime numbers between 1 and 50000", research Sieve of Eratosthenes
Hello fast answer is to create a variable in main, int totaleOfPrimes = 0; for example.
then send it by reference to the fucntion :
Function declaration : void PrintListOfPrime(int value,int* counter);
Function call : void PrintListOfPrime(value,&totaleOfPrimes);
then Increment counter befor printing :
if (ValueIsPrime == 1){
(*counter)++;
printf("%d, ", i);
}
There is no need to iterate the loops for all numbers between 2 and value. You should consider only 2 and odd numbers.
The function can look the following way as it is shown in the demonstrative program below.
#include <stdio.h>
static inline size_t PrintListOfPrime( unsigned int n )
{
size_t count = 0;
printf( "The list of primes:\n" );
for ( unsigned int i = 2; i <= n; i = i != 2 ? i + 2 : i + 1 )
{
int isPrime = 1;
/* Check if the current number i is prime or not */
for ( unsigned int j = 3; isPrime && j <= i / j; j += 2 )
{
/*
* If the number is divisible by any number
* other than 1 and self then it is not prime
*/
isPrime = i % j != 0;
}
/* If the number is prime then print */
if ( isPrime )
{
if ( ++count % 14 == 0 ) putchar( '\n' );
printf( "%u ", i );
}
}
return count;
}
int main(void)
{
unsigned int n = 50000;
size_t count = PrintListOfPrime( n );
printf( "\n\nThere are %zu prime numbers up to %u\n", count, n );
return 0;
}
Run this code in C. It will return the value of a pi(x) function. It is basically the Prime counting function:
#include <stdio.h>
#define LEAST_PRIME 2
#include <math.h>
int main() //works for first 10000 primes.
{
int lower_limit = 2, no_of_sets;
// printf("NUMBER OF SETS: ");
// scanf("%d", &no_of_sets);
int remainder, divisor = 2, remainder_dump, upper_limit; //upper limit to be specified
//by user.
int i = 1;
// printf("SPECIFY LOWER LIMIT: ");
// scanf("%d", &lower_limit);
int number_to_be_checked = lower_limit;
printf("SPECIFY UPPER LIMIT: ");
scanf("%d", &upper_limit);
printf("2\t\t\t\t", number_to_be_checked);
//PRINTS 2.*/
do
{
remainder_dump = 1;
divisor = 2;
do
{
remainder = number_to_be_checked % divisor;
if (remainder == 0)
{
remainder_dump = remainder_dump * remainder; // dumping 0 for rejection.
break;
}
++divisor;
} while (divisor <= number_to_be_checked / divisor); // upto here we know number
is prime or not.
if (remainder_dump != 0)
{
++i;
printf("%d.\t\t\t\t", number_to_be_checked); //print if prime.
};
number_to_be_checked = number_to_be_checked + 1;
} while (number_to_be_checked <= upper_limit);
printf("\n pi(x) = %d \n", i);
//printf("pi function value is %f.", (i - 1) / (log(i - 1)));
float app;
app = upper_limit / (log(upper_limit));
float plot_value;
plot_value = (i) / app;
printf(" BETA FUNCTION VALUE ~ %f", plot_value);
return 0;
}

How to find the nth number?

For an assignment, I have to write code which accepts as input an integer n and outputs the nth 'superunusual' number.
The first few su-numbers are: 22, 23, 26, 33, ... So when the input is 1, the output should be 22. 2 gives 23 and 3 gives 26.
I already have a code that checks if the input number is a su-number, but I can't find a way to calculate the nth number.
So when I now input 22, it says that 22 is a superunusual number.
The code:
/* calculates largest prime factor */
int lprime(int n) {
int max = -1;
while (n % 2 == 0) {
max = 2;
n /= 2;
}
for (int i = 3; i*i <= n; i += 2) {
while (n % i == 0) {
max = i;
n = n / i;
}
}
if (n > 2) {
max = n;
}
return max;
}
/* check unusual number */
int unus(int n) {
/* find largest prime of number */
int factor = lprime(n);
/* Check if largest prime > sqrt(n) */
if ((factor*factor) > n) {
return 1; /* true */
}
else {
return 0; /* false */
}
}
/* delete digit from number */
int del(int num, int n) {
int d = log10(num)+1; /* checks amount of digits */
int revnew = 0;
int new = 0;
for (int i = 0; num != 0; i++) {
int dig = num % 10;
num = num / 10;
if(i == (d - n)) {
continue;
} else {
revnew = (revnew * 10) + dig;
}
}
for (int i = 0; revnew != 0; i++) {
new = (new*10) + (revnew % 10);
revnew = revnew / 10;
}
return new;
}
/* driver code */
int main(int argc, char* v[]) {
int m=22, n;
int x = 0;
int i = 1;
int counter = 0;
scanf("%d", &n);
int d = log10(m)+1;
while (counter < n) {
if (unus(m++)) {
counter++;
}
}
for(unus(m); i < d; i++) {
int nmin = del(m, i);
if (unus(nmin)) {
continue;
} else {
printf("%d is not supurunusual\n", (m-1));
x++;
}
}
if(x==0) {
printf("%d is superunusual!\n", (m-1));
}
return 0;
}
I hope you can understand my code. Otherwise I will explain it better.
Also, I'm quite new to coding, so please don't be to harsh...
You have a function to determine whether a number is unusual, but you do the check whether a number is super-unusual in the body of the main routine. If you extract that code into a proper function:
int is_superunusual(int m)
{
int d = log10(m) + 1;
if (unus(m) == 0) return 0;
for(int i = 0; i < d; i++) { // see footnote
int nmin = del(m, i);
if (unus(nmin) == 0) return 0;
}
return 1;
}
then you can use Eugene's code:
while (counter < n) {
if (is_superunusual(m++)) {
counter++;
}
}
printf("The su number #%d is %d\n", n, m - 1);
Your code tested for unusual numbers, not super-unusual numbers.
Footnote: If you take del(num, n) to mean "remove the nth digit from the end", you can do away with the log10 call in del. You must check all deletions anyway, so the order doesn't really matter here.

Sieve of Eratosthenes and his primes

This is my code:
#include <stdio.h>
int main() {
int number;
int prime[200000] = { 0 };
int i = 0;
int j = 0;
int number1[200] = { 0 };
int t = 0;
int count = 0;
int newprime2[200][200];
int counter[200] = { 0 };
int square;
int count1;
while ((scanf("%d", &number) == 1 ) && (number != 0)) {
number1[count] = number;
++count;
}
count1 = count;
for (count = 0; count < count1; ++count) {
if (number1[count] < 0) {
fprintf(stderr, "Error: Invalid input!\n");
return 100;
break;
}
for (i = 0; i < number1[count]; i++) {
prime[i] = i;
}
for (i = 2; (i < (number1[count])); i++) {
if (prime[i] != 0) {
for (j = 2; (j < (number1[count])); j++) {
{
prime[j*prime[i]] = 0;
if (prime[i] * j > (number1[count]))
break;
}
}
}
}
t = 0;
for (i = 2; i < number1[count]; ++i) {
if ((prime[i] != 0) && (number1[count] % prime[i] == 0)) {
newprime2[count][t] = prime[i];
++t;
}
}
printf("\n");
printf("%i is made out of these primes\n", number1[count]);
counter[count] = 0;
square = 0;
for (i = 0; i < t; ++i) {
while (number1[count] % newprime2[count][i] == 0) {
number1[count] = number1[count] / newprime2[count][i];
square++;
}
counter[count]++;
/* if number isn't made out of any of these primes*/
if (!newprime2[count][i]) { /*Why is this not working?*/
printf("%i ", number1[count]);
}
if (counter[count] == 1) {
printf("%i^%d ", newprime2[count][i], square);
} else {
printf("* %i^%d ", newprime2[count][i], square);
}
square = 0;
}
}
printf("\n");
return 0;
}
For example, my input is: 1 11 120 8 0
Output looks like this:
1 is made out of these primes
11 is made out of these primes
120 is made out of these primes
2^3 * 3^1 * 5^1
8 is made out of these primes
2^3
But Output should looks like this:
1 is made out of these primes
1
11 is made out of these primes
11
...
Statement (!newprime2[count][i]) means that this array is empty right? So why it isn't working? And why I even can't use gcc -pedantic -Wall -Werror -std=c99 -O3 ? Can someone help me?
See this part of your code:
t = 0;
for (i = 2; i < number1[count]; ++i){
if ((prime[i]!=0) && (number1[count] % prime[i]==0)){
newprime2[count][t] = prime[i];
++t;
}
If number1[count] is 1, then the body of the for loops will not execute, sot will keep its value (0). Consequently the body of the next loop
for (i=0; i < t; ++i){
will not execute, too.
For number 11 the body of this loop will execute but it will do nothing as the condition in the if statement will be always false. So it results to the same problem - t will keep its value 0 with the same consequence.
The line
if (!newprime2[count][i])
is not reached if t==0 before the for-loop and that is the case if the input is prime or unity. Just check t and end there if it is zero.
Or check earlier if it is unity or it is in prime already.
I cannot repeat your problems with gcc -pedantic -Wall -Werror -std=c99 -O3.
Your algorithm is both too complicated and approximate:
You do not need to perform a sieve to factorize the numbers, you can just enumerate divisors, composite divisors will have a non zero remainder because their prime factors will have been removed already.
The sieve is incomplete: you go to 200000 which would be overkill if int type is 32 bits (46341 would suffice) and would be too small if int is 64 bits.
Here is a simplified version:
#include <stdio.h>
int main(void) {
int number, i, p, n, factors, count;
int numbers[200];
for (count = 0; count < 200 && scanf("%d", &number) == 1; count++) {
if (number == 0)
break;
if (number < 0) {
fprintf(stderr, "Error: Invalid input!\n");
return 100;
}
numbers[count] = number;
}
for (i = 0; i < count; i++) {
number = numbers[i];
printf("%d is made out of these primes\n", number);
factors = 0;
for (p = 2; p * p <= number; p += 1 + (p & 1)) {
if (number % p == 0) {
n = 0;
factors++;
do {
number /= p;
n++;
} while (number % p == 0);
if (n == 1)
printf("%d ", p);
else
printf("%d^%d ", p, n);
}
}
if (factors == 0 || number != 1)
printf("%d", number);
printf("\n");
}
return 0;
}

Resources