I want to print the following pyramid of number pattern - c

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");
}
}

Related

Print Prime Numbers and Reversed Number

A number and a reversed number form a pair. If both numbers are prime numbers, we call it a reversed prime number pair. For instance, 13 and 31 is a 2 digit reversed prime number pair, 107 and 701 is a 3 digit reversed prime number pairs.
Write a program to output all n (2<=n<=5) digit reversed prime number pairs. If the input is less than 2 or greater than 5, output "Wrong input." and terminate the program. While ouputting , every 5 pairs form a new line, and only output the pair in which the first number is smaller than the second number.
Input: 1
Output: Wrong input.
Input: 3
Output:
(107,701)(113,311)(149,941)(157,751)(167,761)
(179,971)(199,991)(337,733)(347,743)(359,953)
(389,983)(709,907)(739,937)(769,967)
There are 14 results.
Can anyone give me hints how to do this?
I know how to determine if a number is a reversed prime number, but i couldn't understand how to complete this challenge from my friend
#include <stdio.h>
int checkPrime(int n) {
int i, isPrime = 1;
if (n == 0 || n == 1) {
isPrime = 0;
}
else {
for(i = 2; i <= n/2; ++i) {
if(n % i == 0) {
isPrime = 0;
break;
}
}
}
return isPrime;
}
int main (void)
{
int a, reverse = 0, remainder, flag=0;
scanf("%d",&a);
int temp = a;
while (temp!=0) {
remainder = temp%10;
reverse = reverse*10 + remainder;
temp/=10;
}
if (checkPrime(a)==1) {
if (checkPrime(reverse)==1){
printf("YES\n");
flag=1;
}
}
if (flag==0)
printf("NO\n");
}
This will be the correct solution:
#include <stdio.h>
#include <stdbool.h>
#include <math.h>
#include <stdlib.h>
#define MAX_N 100000
int *primes;
int num_primes;
void init_primes() {
int sqrt_max_n = sqrt(MAX_N);
primes = (int *) malloc(sqrt_max_n / 2 * sizeof(int));
num_primes = 0;
primes[num_primes] = 2;
num_primes++;
for (int i = 3; i <= sqrt_max_n; i += 2) {
bool is_prime = true;
for (int j = 0; j < num_primes; j++) {
if (i % primes[j] == 0) {
is_prime = false;
break;
}
}
if (is_prime) {
primes[num_primes] = i;
num_primes++;
}
}
}
int is_prime(int n) {
for (int i = 0; i < num_primes; i++) {
if (primes[i] == n) {
return 1;
}
if (n % primes[i] == 0) {
return 0;
}
}
return 1;
}
int reverse(int n) {
int reversed_n = 0;
while (n > 0) {
reversed_n = reversed_n * 10 + n % 10;
n /= 10;
}
return reversed_n;
}
int main() {
init_primes();
int n;
printf("Enter n (2 <= n <= 5): ");
scanf("%d", &n);
if (n < 2 || n > 5) {
printf("Wrong input.\n");
return 0;
}
int min = (int) pow(10, n - 1);
int max = (int) pow(10, n) - 1;
int count = 0;
for (int i = min; i <= max; i++) {
if (is_prime(i)) {
int reversed_i = reverse(i);
if (i < reversed_i && is_prime(reversed_i)) {
printf("(%d %d)", i, reversed_i);
count++;
if (count % 5 == 0) {
printf("\n");
} else {
printf(" ");
}
}
}
}
return 0;
}
After testing this code I get the same result what you need:
Enter n (2 <= n <= 5): 3
(107 701) (113 311) (149 941) (157 751) (167 761)
(179 971) (199 991) (337 733) (347 743) (359 953)
(389 983) (709 907) (739 937) (769 967)
The init_primes method caches all the required prime numbers until the sqrt of your limit to a dynamic array.
The is_prime method uses that cache for detecting whether a number is prime or not.

Finding the numbers that are palindromic in both base 2 and 10 and summing them up

I need to find the sum of all numbers that are less or equal with my input number (it requires them to be palindromic in both radix 10 and 2). Here is my code:
#include <stdio.h>
#include <stdlib.h>
int pal10(int n) {
int reverse, x;
x = n;
while (n != 0) {
reverse = reverse * 10 + n % 10;
n = n / 10;
}
if (reverse == x)
return 1;
else
return 0;
}
int length(int n) {
int l = 0;
while (n != 0) {
n = n / 2;
l++;
}
return l;
}
int binarypal(int n) {
int v[length(n)], i = 0, j = length(n);
while (n != 0) {
v[i] = n % 2;
n = n / 2;
i++;
}
for (i = 0; i <= length(n); i++) {
if (v[i] == v[j]) {
j--;
} else {
break;
return 0;
}
}
return 1;
}
int main() {
long s = 0;
int n;
printf("Input your number \n");
scanf("%d", &n);
while (n != 0) {
if (binarypal(n) == 1 && pal10(n) == 1)
s = s + n;
n--;
}
printf("Your sum is %ld", s);
return 0;
}
It always returns 0. My guess is I've done something wrong in the binarypal function. What should I do?
You have multiple problems:
function pal10() fails because reverse is not initialized.
function binarypal() is too complicated, you should use the same method as pal10().
you should avoid comparing boolean function return values with 1, the convention in C is to return 0 for false and non zero for true.
you should avoid using l for a variable name as it looks very similar to 1 on most constant width fonts. As a matter of fact, it is the same glyph for the original Courier typewriter font.
Here is a simplified and corrected version with a multi-base function:
#include <stdio.h>
#include <stdlib.h>
int ispal(int n, int base) {
int reverse = 0, x = n;
while (n > 0) {
reverse = reverse * base + n % base;
n = n / base;
}
return reverse == x;
}
int main(void) {
long s = 0;
int n = 0;
printf("Input your number:\n");
scanf("%d", &n);
while (n > 0) {
if (ispal(n, 10) && ispal(n, 2))
s += n;
n--;
}
printf("Your sum is %ld\n", s);
return 0;
}
in the function pal10 the variable reverse is not initialized.
int pal10(int n)
{
int reverse,x;
^^^^^^^
x=n;
while(n!=0)
{
reverse=reverse*10+n%10;
n=n/10;
}
if(reverse==x)
return 1;
else
return 0;
}
In the function binarypal this loop is incorrect because the valid range of indices of an array with length( n ) elements is [0, length( n ) - 1 ]
for(i=0;i<=length(n);i++)
{
if(v[i]==v[j])
{
j--;
}
else
{
break;
return 0;
}
}
And as #BLUEPIXY pointed out you shall remove the break statement from this else
else
{
break;
return 0;
}

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;
}

In C, I would like to print 4 decimal numbers in a row and then print the next 4

#include "stdio.h"
int main() {
int max = 1000;
for (int i = 0; i < max; ++i) {
printf("%d", i);
}
return 0;
}
If max is 1000 then this will print in the format shown below
0123 up to 1000
But I would like to print 4 values per line as shown below:
0123
4567
...
I would like to see the numbers not the just the digits. for a single digit numbers, it should be like this: 0123 for two digit numbers, it should be like this: 11121314 for a three digit numbers, it should be like this: 111112113114 up to 996997998999 up to 1000.
For your loop to print upto and including 1000 for max.size = 1000, you must use the <= operator.
Here is a modified version that will format the output with a maximum of 4 characters per line:
#include <stdio.h>
#include <limits.h>
int main(void) {
struct { int size; } max = { 1000 };
if (max.size >= 0) {
for (int col = 0, i = 0;; i++) {
char buf[2 + sizeof(int) * CHAR_BIT / 3];
int n = snprintf(buf, sizeof buf, "%d", i);
for (int j = 0; j < n; j++) {
putchar(buf[j]);
if (++col == 4) {
putchar('\n');
col = 0;
}
}
if (i == max.size) {
if (col > 0) {
putchar('\n');
}
break;
}
}
}
return 0;
}
It will print:
0123
4567
8910
1112
1718
...
6997
9989
9910
00
EDIT
From your updated question, it is actually much simpler: print a linefeed character after every 4th number, using the modulo operator %.
#include <stdio.h>
int main(void) {
int max = 1000;
for (int i = 0; i < max; ++i) {
printf("%d", i);
if (i % 4 == 3)
putchar('\n');
}
return 0;
}
Just check whether i+1 is divisible by 4 or not. Whenever it is divisible by 4, print a newline.
for (int i = 0; i < max.size; ++i) {
printf("%d", i);
if((i+1)%4 == 0)
printf("\n");
}
You can also do this without using a buffer:
#include <stdio.h>
void print_digit(int number);
int main(void) {
putchar('0');
int i;
for(i = 1; i <= 1000; i++) {
print_digit(i);
}
}
void print_digit(int number) {
static int digit_count = 1; // a zero is already printed
int i;
for(i = 1; i <= number; i *= 10);
for(i /= 10; i; i /= 10) {
putchar('0' + number % (i * 10) / i);
digit_count++;
if(digit_count == 4) {
digit_count = 0;
putchar('\n');
}
}
}
However, I have to admit that this code has nothing to do with elegance, because I don't know how to make print_digit consistent with zero.

How many times a digit is appeared in a number

Well, I wrote the code and everything is fine except one thing.
When I enter that digit number, which has to be upto 10 digits, I recieve in arr[0] various values, for example, if I enter "12345" I get 20, 1 , 1 , 1 , 1 , 1 , 0 ,0 ,0 ,0.
Which is fine from arr[1] to arr[9], but pretty odd in arr[0].
Any ideas?
#include <stdio.h>
#include <conio.h>
#include <math.h>
void main()
{
int i,j,p=0, temp,indexNum, arr[10] = { 0 }, num, level = 10, level2 = 1,maxIndex;
printf("Please enter a digit number (upto 10 digits) \n");
scanf("%d", &num);
temp = num;
while (temp > 0)
{
p++;
temp /= 10;
}
for (i = 0;i < p;i++)
{
temp = num;
while (temp > 0)
{
indexNum = num % level / level2;
arr[indexNum]++;
level *= 10;
level2 *= 10;
temp /= 10;
}
}
for (j = 0; j < 10; j++)
{
printf("%d\n", arr[j]);
}
getch();
}
Here is simplified version of your program:
#include <stdio.h>
#include <math.h>
int main()
{
int i = 0, j = 0, temp = 0, indexNum = 0, num = 0, level = 10;
int arr[10] = {0};
num = 7766123;
temp = num;
if(0 == temp) arr[0] = 1; // Handle 0 input this way
while (temp > 0)
{
indexNum = temp % level;
arr[indexNum]++;
temp /= 10;
}
for (j = 0; j < 10; j++)
{
printf("%d\n", arr[j]);
}
return 0;
}
A few hints to help you:
What does arr[10] = { 0 } actually do?
When you calculate indexNum, you are dividing integers. What happens when the modulus is a one-digit number, and level2 is greater than 1?
It's probably easier to read the input into a string and count digit characters. Something like this (not tested):
std::map<char, int> count;
std::string input;
std::cin >> input;
for (auto iter = input.begin(); iter != input.end(); ++iter) {
if (*iter < 0 || *iter > 9)
break;
else
++count[*iter];
}
for (auto iter = count.begin(); iter != count.end(); ++iter) {
std::cout << *iter << '\n';
}
You need to get rid of your first for loop. Something more like:
#include <stdio.h>
#include <math.h>
using namespace std;
int main()
{
int j;
int temp;
int indexNum;
int arr[10] = { 0 };
int num;
int level = 10;
int level2 = 1;
printf("Please enter a digit number (upto 10 digits) \n");
scanf("%d", &num);
temp = num;
while (temp > 0)
{
indexNum = num % level / level2;
arr[indexNum]++;
level *= 10;
level2 *= 10;
temp /= 10;
}
for (j = 0; j < 10; j++)
{
printf("%d\n", arr[j]);
}
return 0;
}
Check the program below.
void count_digits(unsigned int a, int count[])
{
unsigned int last_digit = 0;
if (a == 0) {
count[0] = 1;
}
while (a != 0)
{
last_digit = a%10;
count[last_digit]++;
a = a/10;
}
}
int main()
{
int count[10]= {0};
unsigned int num = 1122345; /* This is the input, Change it as per your need */
int i = 0;
count_digits(num, count);
for (i = 0; i < 10; i++)
{
printf ("%d: -- %d\n", i, count[i]);
}
return 0;
}

Resources