Given a positive integer N, print all integers between 1 and 2^N such that there is no consecutive 1’s in its Binary representation.
I have below code but it is printing duplicate sometimes. Is it possible to print without duplicates?
#include <stdio.h>
int a[100];
void foo(int i, int size)
{
if (i >= size) {
int i;
for (i=0;i<size;i++)
printf("%d\n", a[i]);
printf("----\n");
return;
}
if (a[i-1] == 1 || a[i-1] == 0)
a[i] = 0;
foo(i+1, size);
if (a[i-1] == 0)
a[i] = 1;
foo(i+1, size);
}
int main(void) {
int i = 0;
int size = 5;
a[i] = 1;
foo(1, size);
return 0;
}
I have this http://ideone.com/cT4Hco python program which uses hash maps to print the elements but I think we can do this without hashmaps also.
Couple of notes:
you shouldn't start the backtracking from index 1. Instead, start from 0 since your numbers would be in the range [0, n-1] in array a
you shouldn't initialize a[0] to 1 since a[0] = 0 is also a valid case.
if (a[i-1] == 1 || a[i-1] == 0) is redundant
Code:
#include <stdio.h>
int a[100];
void foo(int i, int size)
{
if (i >= size) {
int i;
for (i=0;i<size;i++)
printf("%d ", a[i]);
printf("\n----\n");
return;
}
a[i] = 0;
foo(i+1, size);
if ( i == 0 || a[i-1] == 0) {
a[i] = 1;
foo(i+1, size);
}
}
int main(void) {
int i = 0;
int size = 5;
foo(0, size);
return 0;
}
You might also want to filter the solution 0 0 0 ... 0 during the printing since you need only the numbers from 1 to 2^n. If 2^n is included you should also print it. The backtracking considers the numbers 0, ...., 2^n-1
Related
I am hoping to mimic a Python for loop with the range() function in C. I'd like to accomplish a task an increasing number of times each loop until I reach the value of a given variable, in this case 5 (for the variable h). Here it is in Python:
x = 5
y = 0
while x > y:
for i in range(y+1):
print("#",end='')
print('')
y+=1
Output:
#
##
###
####
#####
I was able to accomplish the opposite (executing something a decreasing number of times) in C, as below:
{
int h = 5;
while (h > 0)
{
for (int i = 0; i < h; i++)
{
printf("#");
}
printf("\n");
h--;
}
}
Output:
#####
####
###
##
#
When I've attempted the top version in C, with the increasing number of executions, I run into the problem of not knowing how to control the various incrementing and decrementing variables.
I suggest you should think simply:
Increment up the number of # to print
Use loop to print that number of #
#include <stdio.h>
int main(void)
{
int h = 5;
for (int c = 1; c <= h; c++) // the number of # to print
{
for (int i = 0; i < c; i++)
{
printf("#");
}
printf("\n");
}
return 0;
}
Another way is simply writing in just the same way as the Python version:
#include <stdio.h>
int main(void)
{
int x = 5;
int y = 0;
while (x > y)
{
for (int i = 0; i < y+1; i++)
{
printf("#");
}
printf("\n");
y += 1;
}
return 0;
}
The solution in C:
#include <stdio.h>
int main ()
{
int x = 5;
int y = 0;
while (x > y)
{
for (int i=0;i<y+1;i++)
{
printf("#");
}
printf("\n");
}
return 0;
}
In Python, in the for loop, the variable is initialized as zero and increments by 1 by default. But in C, you need to do it explicitly.
My problem is fairly simple, I am trying to calculate the nth prime number, however between the two methods that I have coded, the one that I expect to run faster appears to be slower. Which honestly makes no sense. I initially coded the solution using python, here is the code:
import time
import math
start1 = time.time()
primes = [2]
count = 3
primes_len = 1
while primes_len <= 10001:
is_prime = True
for i in range(primes_len):
if count % primes[i] == 0:
is_prime = False
break
if is_prime:
primes_len += 1
primes.append(count)
count += 2
print(primes[-1])
end1 = time.time()
start2 = time.time()
listPrime = [2]
upTo = 1000000
isPrime = True
for sayi in range(3, upTo, 2):
for bölen in range(2,int(math.sqrt(sayi)+1)):
if (sayi % bölen) == 0:
isPrime = False
break
else:
isPrime = True
if isPrime == True :
listPrime.append(sayi)
if len(listPrime) == 10001:
break
print(listPrime[-1])
end2 = time.time()
print(end1-start1)
print(end2-start2)
Even though I expected the first algorithm to run faster(since it only tests for known primes and thus should require less calculation), the second one was significantly more eficcient. Thinking it was a weird python thing that caused the unexpected result, I coded them both in C, here it is:
The first one:
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main(int argc, char **argv){
if(argc != 2){
printf("You must provide one argument as the nth prime to calculate");
return 0;
}
clock_t begin = clock();
long LIMIT = strtol(argv[1], NULL, 10);;
int count = 3;
int primes_found = 1;
int primes[LIMIT];
primes[0] = 2;
int is_prime;
while(primes_found < LIMIT){
is_prime = 1;
for(int i = 0; i < primes_found; i++){
if(count % primes[i] == 0){
is_prime = 0;
break;
}
}
if(is_prime == 1){
primes[primes_found] = count;
primes_found += 1;
}
count += 2;
}
printf("%d\n", primes[LIMIT - 1]);
clock_t end = clock();
double time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
printf("%f\n", time_spent);
return 0;
}
The second one:
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <math.h>
int main(int argc, char **argv){
if(argc != 2){
printf("You must provide one argument as the nth prime to calculate");
return 0;
}
clock_t begin = clock();
long LIMIT = strtol(argv[1], NULL, 10);;
int count = 3;
int primes_found = 1;
int primes[LIMIT];
primes[0] = 2;
int is_prime;
while(primes_found < LIMIT){
is_prime = 1;
for(int i = 2; i <= (int) sqrt(count); i++){
if(count % i == 0){
is_prime = 0;
break;
}
}
if(is_prime == 1){
primes[primes_found] = count;
primes_found += 1;
}
count += 2;
}
printf("%d\n", primes[LIMIT - 1]);
clock_t end = clock();
double time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
printf("%f\n", time_spent);
return 0;
}
Which behaved the same way. Honestly, this makes absolutely no sense to me, would appreciate any opinions on it.
Consider the difference between loops
for(int i = 0; i < primes_found; i++){
And
for(int i = 2; i <= (int) sqrt(count); i++){
When the number being tested for a prime, let us call test, the first iterates against all known smaller primes primes[i]. When primes[i]*primes[i] > test, that is wasted time.
The second loop iterates all values up to sqrt(test). This is inefficient in that many division candidates are not primes themselves.
Apparently, the inefficiency of the first is worst.
An alternative to is iterate using the prime list, but stop when primes[i]*primes[i] > test 1.
Also see Sieve of Eratosthenes for a likely faster approach.
1 Even better: use primes[i] > test/primes[i] to avoid overflow.
In your first one, you forgot to only go up to the square root.
Basically my problem is that I'm trying to manually translate stuff that Python3 does easily into a C program. My first hurdle is literally input comprehension. Here is the sample input:
5
12
34 10
22 20 55
123 30 x 99
So as we can see, there are numbers, spaces, and characters in this input. I handled it in Python pretty easily, like so:
n = int(input()) #first line is always a single integer
matrix = [[' ' for i in range(n)] for j in range(n)] #declaring matrix of just space chars
for i in range(1,n):
line = input().split(' ') #gets rid of all spaces
for j in range(len(line)):
try:
matrix[i][j] = int(line[j])
matrix[j][i] = int(line[j]) #mirrors same value on opposite part of the matrix
except:
matrix[i][j] = 'x'
matrix[j][i] = 'x'
This results in the following matrix:
[[' ', 12, 34, 22, 123]
[12, ' ', 10, 20, 30]
[34, 10, ' ', 55, 'x']
[22, 20, 55, ' ', 99]
[123, 30, 'x', 99, ' ']]
So basically, I want to figure out how to do this in C. I have seen posts about how to read inputs dynamically, how to receive space-separated integers, and how to malloc integer space, but I have no idea how to put all of that stuff together. I would really appreciate some help. Ideally I want to store all these integers into a 2D array of integers like shown above.
EDIT: This is as far as I've gotten (code butchered from other people's helpful answers):
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
int main()
{
int n; //number of cities
scanf("%d", &n);
printf("%d\n", n);
int *matrix = (int*)malloc(n*n*sizeof(int));
int i=0, j=0;
int *line = matrix;
char temp;
for (int k=0;k<n;k++)
{
do {
scanf("%d%c", &line[i], &temp);
i++;
} while(temp != '\n');
for(j=0; j<i; j++) {
printf("%d ", matrix[j]);
}
printf("\n");
}
free(matrix);
free(n);
return 0;
}
Output of this code:
5
5
12
12
34 10
12 34 10
22 20 55
12 34 10 22 20 55
123 30 x 99
^From above, first '5' is my input, second '5' is outputted, first '12' is my input, second is outputted, and so on. Code breaks in the last line. I understand that each time, it dumps everything stored in the 'buffer' that is the int * matrix. I don't know how to handle other characters like the 'x'. Ideally I would like to replace the 'x' in the matrix with a -1 or something.
I think it is really a mistake to mix scanf with getchar, but I believe the correct way to avoid scanf here is to pass n as a parameter (eg, read it from argv[1] rather than from the input stream). Also, your python is not really a matrix, but is a list of lists, and it would probably be cleaner to use a list of lists in the C implementation. But here is one approach to using a large array.
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
struct entry {
enum { unknown, number, character } type;
union {
int v;
char x;
} value;
};
static int
die(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
vfprintf(stderr, fmt, ap);
va_end(ap);
fputc('\n', stderr);
exit(EXIT_FAILURE);
}
int
main(void) {
int n, c = '\n', p = EOF, row = 0;
if( scanf("%d", &n) != 1 || n < 1 ) {
die("Invalid input in row %d (%c)", row, c);
}
struct entry *matrix = calloc(n * n, sizeof *matrix);
struct entry *t = matrix - 1, *e = matrix + n * n;
while( (c = getchar()) != EOF) {
if( isdigit(c) ) {
if( t->type == character ) {
die("Invalid input in row %d (%c)", row, c);
}
t->type = number;
t->value.v = t->value.v * 10 + c - '0';
} else if( isspace(c) && c != p ) {
t += 1;
if( t >= e ) {
die("Invalid input in row %d (%c)", row, c);
}
if( c == '\n' ) {
t->type = character;
t->value.x = ' ';
t = matrix + n * ++row;
}
} else {
if( t->type != unknown ) {
die("Invalid input in row %d (%c)", row, c);
}
t->type = character;
t->value.x = c;
}
p = c;
}
/* Display the matrix */
for( int i = 0; i < n; i++ ) {
for( int j = 0; j < n; j++ ) {
t = matrix + (( j > i ) ? (n * j + i) : (n * i + j));
switch( t->type ) {
case number:
printf("%8d", t->value.v);
break;
case unknown:
printf("%8s", "??");
break;
case character:
printf(" '%c'", t->value.x);
}
}
putchar('\n');
}
}
This solution is not as robust against whitespace issues in the input as a scanf solution would be, and does not handle runs of space or mixed space and tabs. Fixing that is left as an exercise for the reader.
I wrote a word-list generator originally in C some while ago, which took about 2 days. I used a dedicated int array to store the indices and incremented them using the idea of number bases. Here is my source code:
/*
* Generates word lists from a character set
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int power(int x, int y);
void ntoarray(int n, int base, int seq[], int len);
void setchar(char charset[], char word[], int indices[]);
int main(int argc, char *argv[])
{
// checks arguments
if (argc != 4)
{
printf("Usage: %s start_length end_length charset", argv[0]);
return 1;
}
else
{
// loops from start length to end length
for (int lenword = atoi(argv[1]), lim = atoi(argv[2]); lenword <= lim; lenword++)
{
// pointer to character set
char *charset = argv[3];
// length of the character set
int lencharset = strlen(charset);
// array for the word
char word[lenword + 1];
word[lenword] = '\0';
// array for storing the indices to generate the word from the character set
int indices[lenword];
// number to convert to required base
int n = 0;
// repetition is allowed so the number of times to loop is number^choice
for (int i = 0; i < power(lencharset, lenword); i++)
{
// converts number to an integer array with length of the charset as the base
ntoarray(n++, lencharset, indices, lenword);
// sets the word according to the indices array
setchar(charset, word, indices);
// prints the word
printf("%s\n", word);
}
}
return 0;
}
}
// simple power algorithm which raises x to the power y
int power(int x, int y)
{
int n = 1;
for (int i = 0; i < y; i++)
n *= x;
return n;
}
// converts n to the required base and stores it in an integer array
void ntoarray(int n, int base, int seq[], int len)
{
int i = len - 1;
memset(seq, 0, sizeof(int) * len);
while (i >= 0 && n >= base)
{
int r = n % base;
n /= base;
seq[i--] = r;
}
seq[i] = n;
}
// sets the word by combining the data from the indices array and the charset array
void setchar(char charset[], char word[], int indices[])
{
int len = strlen(word);
for (int i = 0; i < len; i++)
{
word[i] = charset[indices[i]];
}
}
Now I have rewritten it in python3 using a similar idea, but it took only about an hour.
"""
Generates word lists from a character set.
"""
import argparse
def main():
# checks arguments
parser = argparse.ArgumentParser()
parser.add_argument("start_length", help = "starting length for your words", type = int)
parser.add_argument("end_length", help = "ending length for your words", type = int)
parser.add_argument("charset", help = "character set to be used", type = str)
args = parser.parse_args()
charset = args.charset
len_charset = len(charset)
# loops from start_length to end_length
for length in range(args.start_length, args.end_length + 1):
# initializes indices list
indices = [0] * length
# prints the word
print(genword(charset, indices))
# increments the indices list and prints the word until the limit
# repetition is allowed so the number of loops is base ^ length - 1 (-1 for the printed word)
for i in range(len_charset ** length - 1):
inc_seq(indices, len_charset)
print(genword(charset, indices))
def inc_seq(seq, base, index=-1):
"""
Increments a number sequence with a specified base by one.
"""
if seq[index] < base - 1:
seq[index] += 1
else:
inc_seq(seq, base, index - 1)
seq[index] = 0
def genword(charset, indices):
"""
Generates a word by combining a character set and a list of indices.
"""
return "".join([charset[i] for i in indices])
if __name__ == "__main__":
main()
There is a notable difference: In C, I incremented an intermediary number n and used it to modify the int array; in python, I harnessed the power of negative indices to directly increment the int list.
I learned to code mostly by self-study (i.e. reading books and using online resources), but I do not yet know how to analyze algorithms properly. So my question is: Which version is more efficient, in terms of time and space?
what is the fastest way to compute the greatest common divisor of n numbers?
Without recursion:
int result = numbers[0];
for(int i = 1; i < numbers.length; i++){
result = gcd(result, numbers[i]);
}
return result;
For very large arrays, it might be faster to use the fork-join pattern, where you split your array and calculate gcds in parallel. Here is some pseudocode:
int calculateGCD(int[] numbers){
if(numbers.length <= 2){
return gcd(numbers);
}
else {
INVOKE-IN-PARALLEL {
left = calculateGCD(extractLeftHalf(numbers));
right = calculateGCD(extractRightHalf(numbers));
}
return gcd(left,right);
}
}
You may want to sort the numbers first and compute the gcd recursively starting from the smallest two numbers.
C++17
I have written this function for calculating gcd of n numbers by using C++'s inbuilt __gcd(int a, int b) function.
int gcd(vector<int> vec, int vsize)
{
int gcd = vec[0];
for (int i = 1; i < vsize; i++)
{
gcd = __gcd(gcd, vec[i]);
}
return gcd;
}
To know more about this function visit this link .
Also refer to Dijkstra's GCD algorithm from the following link. It works without division. So it could be slightly faster (Please correct me if I am wrong.)
You should use Lehmer's GCD algorithm.
How about the following using Euclidean algorithm by subtraction:
function getGCD(arr){
let min = Math.min(...arr);
let max= Math.max(...arr);
if(min==max){
return min;
}else{
for(let i in arr){
if(arr[i]>min){
arr[i]=arr[i]-min;
}
}
return getGCD(arr);
}
}
console.log(getGCD([2,3,4,5,6]))
The above implementation takes O(n^2) time. There are improvements that can be implemented but I didn't get around trying these out for n numbers.
If you have a lot of small numbers, factorization may be actually faster.
//Java
int[] array = {60, 90, 45};
int gcd = 1;
outer: for (int d = 2; true; d += 1 + (d % 2)) {
boolean any = false;
do {
boolean all = true;
any = false;
boolean ready = true;
for (int i = 0; i < array.length; i++) {
ready &= (array[i] == 1);
if (array[i] % d == 0) {
any = true;
array[i] /= d;
} else all = false;
}
if (all) gcd *= d;
if (ready) break outer;
} while (any);
}
System.out.println(gcd);
(works for some examples, but not really tested)
Use the Euclidean algorithm :
function gcd(a, b)
while b ≠ 0
t := b;
b := a mod b;
a := t;
return a;
You apply it for the first two numbers, then the result with the third number, etc... :
read(a);
read(b);
result := gcd(a, b);
i := 3;
while(i <= n){
read(a)
result := gcd(result, a);
}
print(result);
Here below is the source code of the C program to find HCF of N numbers using Arrays.
#include<stdio.h>
int main()
{
int n,i,gcd;
printf("Enter how many no.s u want to find gcd : ");
scanf("%d",&n);
int arr[n];
printf("\nEnter your numbers below :- \n ");
for(i=0;i<n;i++)
{
printf("\nEnter your %d number = ",i+1);
scanf("%d",&arr[i]);
}
gcd=arr[0];
int j=1;
while(j<n)
{
if(arr[j]%gcd==0)
{
j++;
}
else
{
gcd=arr[j]%gcd;
i++;
}
}
printf("\nGCD of k no.s = %d ",gcd);
return 0;
}
For more refer to this website for further clarification.......
You can use divide and conquer. To calculate gcdN([]), you divide the list into first half and second half. if it only has one num for each list. you calculate using gcd2(n1, n2).
I just wrote a quick sample code. (assuming all num in the list are positive Ints)
def gcdN(nums):
n = len(nums)
if n == 0: return "ERROR"
if n == 1: return nums[0]
if n >= 2: return gcd2(gcdN(nums[:n//2]), gcdN(nums[n//2:]))
def gcd2(n1, n2):
for num in xrange(min(n1, n2), 0, -1):
if n1 % num == 0 and n2 % num == 0:
return num
Here's a gcd method that uses the property that gcd(a, b, c) = gcd(a, gcd(b, c)).
It uses BigInteger's gcd method since it is already optimized.
public static BigInteger gcd(BigInteger[] parts){
BigInteger gcd = parts[0];
for(int i = 1; i < parts.length; i++)
gcd = parts[i].gcd(gcd);
return gcd;
}
//Recursive solution to get the GCD of Two Numbers
long long int gcd(long long int a,long long int b)<br>
{
return b==0 ? a : gcd(b,a%b);
}
int main(){
long long int a,b;
cin>>a>>b;
if(a>b) cout<<gcd(a,b);
else cout<<gcd(b,a);
return 0;
}
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
class GCDArray{
public static int [] extractLeftHalf(int [] numbers)
{
int l =numbers.length/2;
int arr[] = Arrays.copyOf(numbers, l+1);
return arr;
}
public static int [] extractRightHalf(int [] numbers)
{
int l =numbers.length/2;
int arr[] = Arrays.copyOfRange(numbers,l+1, numbers.length);
return arr;
}
public static int gcd(int[] numbers)
{
if(numbers.length==1)
return numbers[0];
else {
int x = numbers[0];
int y = numbers[1];
while(y%x!=0)
{
int rem = y%x;
y = x;
x = rem;
}
return x;
}
}
public static int gcd(int x,int y)
{
while(y%x!=0)
{
int rem = y%x;
y = x;
x = rem;
}
return x;
}
public static int calculateGCD(int[] numbers){
if(numbers.length <= 2){
return gcd(numbers);
}
else {
int left = calculateGCD(extractLeftHalf(numbers));
int right = calculateGCD(extractRightHalf(numbers));
return gcd(left,right);
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int arr[] = new int[n];
for(int i=0;i<n;i++){
arr[i]=sc.nextInt();
}
System.out.println(calculateGCD(arr));
}
}
**
Above is the java working code ..... the pseudo code of which is
already mention by https://stackoverflow.com/users/7412/dogbane
**
A recursive JavaScript (ES6) one-liner for any number of digits.
const gcd = (a, b, ...c) => b ? gcd(b, a % b, ...c) : c.length ? gcd(a, ...c) : Math.abs(a);
This is what comes off the top of my head in Javascript.
function calculateGCD(arrSize, arr) {
if(!arrSize)
return 0;
var n = Math.min(...arr);
for (let i = n; i > 0; i--) {
let j = 0;
while(j < arrSize) {
if(arr[j] % i === 0) {
j++;
}else {
break;
}
if(j === arrSize) {
return i;
}
}
}
}
console.log(generalizedGCD(4, [2, 6, 4, 8]));
// Output => 2
Here was the answer I was looking for.
The best way to find the gcd of n numbers is indeed using recursion.ie gcd(a,b,c)=gcd(gcd(a,b),c). But I was getting timeouts in certain programs when I did this.
The optimization that was needed here was that the recursion should be solved using fast matrix multiplication algorithm.