#include <stdio.h>
#include <cs50.h>
int main(void)
{
int n;
do
{
n = get_int("height: ");
}
while(n<1&&n>8);
for (int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
printf("#");
}
printf("\n");
}
}
im writing a program to print a square with hashes,but my while in the Do loop wont work.
i want it to accept values only between 1 and 8 inclusive,but it wont work and wouldnt prompt again if i enter values out of the parameter.but it works if I only put a single parameter in the while loop e.g. n<1.
please help me,im a beginner.
The answer is very easy and it is not related to the programming only simple math and logic
while(n<1&&n>8)
If n is lower than 1 it cannot be larger than 8 at the same time.
Reason for not working : while( n<1 && n>8); See the image for clarity. There is no value in the intersection. I mean there is no number, less than one and greater than 8.
Solution : Use while(n < 1 || n > 8); for n values between 1 and 8 inclusive.
There is no such a number that would be simultaneously less than 1 and greater than 8.:)
n<1&&n>8
A simple way to write correctly the condition of the loop is to write at first the condition that a number shall satisfy. That is
1 <= n && n <= 8
and then to apply negation to the condition
do { /*...*/ } while ( !( 1 <= n && n <= 8 ) );
Then using rules for logical operations you can write for example
do { /*...*/ } while ( !( 1 <= n ) || !( n <= 8 ) );
and at last
do { /*...*/ } while ( ( 1 > n ) || ( n > 8 ) );
or
do { /*...*/ } while ( n < 1 || n > 8 );
Related
output is 0 when entered 1001 or something greater than it.
it should give 0 when the number isn't abundant and should exit if entered number is greater than the limit ,have tried using goto exit.
#include <stdio.h>
void main()
{
int n;
printf("Enter the number\n");
scanf("%d", &n);
int i, sum = 0;
if (1 <= n <= 1000)
{
for (i = 2; i < n; i++)
{
if (n % i == 0)
sum = sum + i;
}
(sum > n) ? printf("1") : printf("0");
}
else
return;
}
The condition in this if statement
if (1 <= n <= 1000)
is equivalent to
if ( ( 1 <= n ) <= 1000)
the result of the sub-expression 1 <= n is either 0 or 1. So this value is in any case less than 1000.
From the C Standard (6.5.8 Relational operators)
6 Each of the operators < (less than), > (greater than), <= (less than
or equal to), and >= (greater than or equal to) shall yield 1 if the
specified relation is true and 0 if it is false. The result has type
int.
You need to write
if (1 <= n && n <= 1000)
using the logical AND operator.
Pay attention to that according to the C Standard the function main without parameters shall be declared like
int main( void )
So this function is just supposed to return 0 if not prime and 1 if prime. Am I seeing something wrong? for example, when I give it 39, it says it returns 1 although 39 is not a prime.
int is_prime(int number){
if (number == 2) {
return 1;
}
else{
for(loop_counter ; loop_counter < number ; loop_counter++){
if(number%loop_counter == 0){
return 0;
}
else{
return 1;
}
}
}
}
In this loop
for(loop_counter ; loop_counter < number ; loop_counter++){
there is used an undeclared variable loop_counter. If it is a global variable then it shall not be used in the function because at least it is unclear what is its value.
Also within the loop you are interrupting its iterations as soon as number%loop_counter != 0. But this does not mean that the number is prime.
And if the user will pass a negative number or zero then the function will have undefined behavior.
The function can be defined the following way
int is_prime( unsigned int n )
{
int prime = n % 2 == 0 ? n == 2 : n != 1;
for ( unsigned int i = 3; prime && i <= n / i; i += 2 )
{
prime = n % i != 0;
}
return prime;
}
The function at first excludes all even numbers except 2 because even numbers are not prime numbers. And it also excludes the number 1 because the number 1 is not prime by the definition.
int prime = n % 2 == 0 ? n == 2 : n != 1;
So within the loop there is no sense to consider divisors that are even.
for ( unsigned int i = 3; prime && i <= n / i; i += 2 )
^^^^^^
Then within the loop there is a check whether the given odd number n is divisible by an odd divisor
prime = n % i != 0;
If n % i is equal to 0 then the variable prime gets the value 0 and the loop stops its iterations due to the condition in the loop.
for ( unsigned int i = 3; prime && i <= n / i; i += 2 )
^^^^^
that can be rewritten also like
for ( unsigned int i = 3; prime != 0 && i <= n / i; i += 2 )
^^^^^^^^^^
regarding:
for(loop_counter ; loop_counter < number ; loop_counter++){
the variable: loop_counter is not initialized (nor even declared)
Perhaps you meant:
for( int loop_counter = 0; loop_counter < number ; loop_counter++){
The following proposed code:
cleanly compiles
performs the desired functionality
is NOT the fastest/best way to check if a number is prime. Rather it is a brute force method
The OPs posted code has several problems as discussed in comments to the OPs question, so will not be repeated here.
Now, the proposed code:
int is_prime(int number)
{
for( int loop_counter = 2 ; loop_counter < number ; loop_counter++)
{
if(number%loop_counter == 0)
{
return 0;
}
}
return 1;
}
To test two 32-bit integers, m whose factorial is m! can be divisible by n. If it can, the function divides() returns 1, otherwise 0.
As the codes below, the problem is when m = 2010000, error happened. Could you please explain why?
#include <stdio.h>
long factorial(long n){
if((n == 0) || (n == 1)) return 1;
else{
return (n * factorial(n-1));
}
}
int divides (long n,long m)
{
long facN;
printf("n=%ld ",n);
facN = factorial(n);
if(m != 0){
if(facN == 1) return 0;
else{
if(facN % m == 0) return 1;
else if((facN % m) != 0)return 0;
}
}
else if(m == 0) return 0;
}
int main()
{
printf("%d", divides(2000000,1));
}
You need to compute the factorial with the modulus already taken into account. Using the following identity:
(a * b) % n = ((a % n) * (b % n)) % n
we can compute the factorial as:
m! % n = (((((1 % n) * 2) % n) * 3) % n) ...) % n
A 32-bit integer can only store factorials from 0 to 12.
1*2*3*4*5*6*7*8*9*10*11*12
479001600
1*2*3*4*5*6*7*8*9*10*11*12*13
6227020800
Given that 69! is of the order of 10^98 you are probably looking at value overflows but you might also be looking at running out of memory/stack as you will be nesting 2 million deep in your recursion.
Also your check if((facN % m) != 0) is redundant as it is called in the else to if(facN % m == 0)
If your cause is all about finding out whether if m! for an m is divisible by an n, do not calculate the factorial at all.
Rather split n to its factors, check if there are enough many of those inside the numbers ranging from 1 to m, inclusive.
For example; for m = 7 and n = 28, the process should be like the following:
n % 2 == 0 ? yes
n /= 2
2 * 1 <= m ? yes
n % 2 == 0 still? yes
n /= 2
2 * 2 <= m ? yes
n % 2 == 0 still? no
n % 3 == 0 ? no
...
n % 7 == 0 ? yes
n /= 7
7 <= m ? yes
n reached 1, return 1
Something like this. If you cannot manage to write this, then you probably shouldn't be dealing with that question yet. Still, if you want, leave a comment, I can edit my answer to include a working code.
I am adding a working example, using the logic above to display whether n is a divisor of m!, just to assure you that this thing does indeed work:
#include <stdio.h>
// this function basically compares the powers of the
// prime divisors of factee and divisor
// ... returns 1 if the powers in divisor are
// ... less than or equal to the powers in factee
// ... returns 0 otherwise
int divides( long factee, long divisor ){
int amount;
for ( int i = 2; i <= factee; i++ ){
if ( divisor % i )
continue;
amount = 0;
int copy = factee;
while ( copy ){
copy /= i;
amount += copy;
}
while ( divisor % i == 0 ){
if ( !amount )
return 0;
amount--;
divisor /= i;
}
if ( divisor == 1 )
return 1;
}
return 0;
}
int main( )
{
printf( "%d", divides( 20, 10000 ) );
getchar( );
return 0;
}
amount variable calculates the amount of i there are inside the m!. In the while loop in which it gets calculated, with the first cycle, the amount of is are added, then with the second cycle, the amount of i * is are added, and so on, until there aren't any.
For example, with m = 5 and i = 2, m / 2 is 2, which is the amount of occurrence of the factor 2 inside the 5!. Then m / 2 / 2, which is 1, is the amount of occurrence of the factor 2 * 2 == 4 inside the 5!. Then m / 2 / 2 == 0 is the count for 2 * 2 * 2 == 8, which causes the loop to end due to the 0 encounter.
Edit
I fixed something important in the code, removed the outermost while which was there for nothing, something I had put as I started and apparently forgot to remove, causing potential infinite-loops. Here I also made an improved version of the function that generally runs faster than the one above:
#include <stdio.h>
// this function basically compares the powers of the
// prime divisors of factee and divisor
// ... returns 1 if the powers in divisor are
// ... less than or equal to the powers in factee
// ... returns 0 otherwise
int divides( long factee, long divisor ){
int amount;
if ( divisor % 2 == 0 ){
amount = 0;
int copy = factee;
while ( divisor % 2 == 0 ){
if ( !amount ){
copy /= 2;
if ( !copy )
return 0;
amount += copy;
}
amount--;
divisor /= 2;
}
if ( divisor == 1 )
return 1;
}
for ( int i = 3; i <= factee; i += 2 ){
if ( divisor % i )
continue;
amount = 0;
int copy = factee;
while ( divisor % i == 0 ){
if ( !amount ){
copy /= i;
if ( !copy )
return 0;
amount += copy;
}
amount--;
divisor /= i;
}
if ( divisor == 1 )
return 1;
}
return 0;
}
int main( ) {
printf( "%d", divides( 34534564, 345673455 ) );
//printf( "%d", divides( 20, 10000 ) );
getchar( );
return 0;
}
long can support a value in the range of -2,147,483,647 to 2,147,483,647, here 2000000! is out of the range of long, that is why it is showing error.
What is the efficient way in C program to check if integer is one in which each digit is either a zero or a one ?
example 100 // is correct as it contains only 0 or 1
701 // is wrong
I tried for
int containsZero(int num) {
if(num == 0)
return 0;
if(num < 0)
num = -num;
while(num > 0) {
if(num % 10 == 0)
return 0;
num /= 10;
}
return -1;
}
int containsOne(int num) {
if(num == 0)
return 0;
if(num < 0)
num = -num;
while(num > 0) {
if(num % 10 == 1)
return 0;
num /= 10;
}
return -1;
}
You can peel of every digit and check it. This takes O(n) operations.
int input;
while (input != 0)
{
int digit = input %10; //get last digit using modulo
input = input / 10; //removes last digit using div
if (digit != 0 && digit != 1)
{
return FALSE;
}
}
return TRUE;
Well, in the worst case you have to check every digit, so you cannot have an algorithm better than O(d), where d is the number of digits.
The straight-forward approach satisfies this:
int n = 701;
while ( n != 0 && (n % 10) <= 1 )
{
n /= 10;
}
if ( (n % 10) > 1 )
{
printf("Bad number\n");
}
else
{
printf("Good number\n");
}
This assumes positive numbers though. To put it into a general function:
int tester(int n)
{
if ( n < 0 )
{
n = -n;
}
while ( n != 0 && (n % 10) <= 1 )
{
n /= 10;
}
return ( (n % 10) <= 1 );
}
Demo: http://ideone.com/jWyLdl
What are we doing here? We check if the last decimal digit (n % 10) is either 0 or 1, then cut of the last digit by dividing by ten until the number is 0.
Now of course there is also another approach.
If you are guaranteed to have e.g. always 32bit integers, a look-up table isn't that large. I think it may be around 2048 entries, so really not that big.
You basically list all valid numbers:
0
1
10
11
100
101
110
111
...
Now you simply search through the list (a binary search is possible, if the list is sorted!). The complexity with linear search would be, of course, worse than the approach above. I suspect binary search beeing still worse in actual performance, as you need to jump a lot in memory rather than just operating on one number.
Anything fancy for such a small problem is most probably overkill.
The best solution I can think of, without using strings:
while(n)
{
x = n%10;
if(x>1)
return -1;
n /= 10;
}
return 0;
Preamble
Good straightforward algorithms shown in other answer are O(n), being n the number for the digits. Since n is small (even using 64bit integer we won't have more than 20 digits), implementing a "better" algorithm should be pondered, and meaning of "efficient" argued; given O(n) algorithms can be considered efficient.
"Solution"
We can think about sparse array since among 4 billions of numbers, only 2^9 (two symbols, 9 "positions") have the wanted property. I felt that some kind of pattern should emerge from bits, and so there could be a solution exploiting this. So, I've dumped all decimal numbers containing only 0 and 1 in hex, noticed a pattern and implemented the simplest code exploiting it — further improvements are surely possible, e.g. the "table" can be halved considering that if x is even and has the property, then x+1 has the property too.
The check is only
bool only01(uint32_t n)
{
uint32_t i = n & 0xff;
uint32_t r = n >> 8;
return map01[i][0] == r || map01[i][1] == r;
}
The full table (map01) and the test code are available at this gist.
Timing
A run of the test ("search" for numbers having the property between 0 and 2 billions — no reason to go beyond) with my solution, using time and redirecting output to /dev/null:
real 0m4.031s
user 0m3.948s
A run of the same test with another solution, picked from another answer:
real 0m15.530s
user 0m15.221s
You work with base 10, so, each time check the % 10:
int justOnesAndZeros(int num) {
while ( num )
{
if ( ( num % 10 != 1 ) && ( num % 10 != 0 ) )
{
return FALSE;
}
num /= 10;
}
return TRUE;
}
int prime(unsigned long long n){
unsigned val=1, divisor=7;
if(n==2 || n==3) return 1; //n=2, n=3 (special cases).
if(n<2 || !(n%2 && n%3)) return 0; //if(n<2 || n%2==0 || n%3==0) return 0;
for(; divisor<=n/divisor; val++, divisor=6*val+1) //all primes take the form 6*k(+ or -)1, k[1, n).
if(!(n%divisor && n%(divisor-2))) return 0; //if(n%divisor==0 || n%(divisor-2)==0) return 0;
return 1;
}
The code above is something a friend wrote up for getting a prime number. It seems to be using some sort of sieving, but I'm not sure how it exactly works. The code below is my less awesome version. I would use sqrt for my loop, but I saw him doing something else (probably sieving related) and so I didn't bother.
int prime( unsigned long long n ){
unsigned i=5;
if(n < 4 && n > 0)
return 1;
if(n<=0 || !(n%2 || n%3))
return 0;
for(;i<n; i+=2)
if(!(n%i)) return 0;
return 1;
}
My question is: what exactly is he doing?
Your friend's code is making use of the fact that for N > 3, all prime numbers take the form (6×M±1) for M = 1, 2, ... (so for M = 1, the prime candidates are N = 5 and N = 7, and both those are primes). Also, all prime pairs are like 5 and 7. This only checks 2 out of every 3 odd numbers, whereas your solution checks 3 out of 3 odd numbers.
Your friend's code is using division to achieve something akin to the square root. That is, the condition divisor <= n / divisor is more or less equivalent to, but slower and safer from overflow than, divisor * divisor <= n. It might be better to use unsigned long long max = sqrt(n); outside the loop. This reduces the amount of checking considerably compared with your proposed solution which searches through many more possible values. The square root check relies on the fact that if N is composite, then for a given pair of factors F and G (such that F×G = N), one of them will be less than or equal to the square root of N and the other will be greater than or equal to the square root of N.
As Michael Burr points out, the friend's prime function identifies 25 (5×5) and 35 (5×7) as prime, and generates 177 numbers under 1000 as prime whereas, I believe, there are just 168 primes in that range. Other misidentified composites are 121 (11×11), 143 (13×11), 289 (17×17), 323 (17×19), 841 (29×29), 899 (29×31).
Test code:
#include <stdio.h>
int main(void)
{
unsigned long long c;
if (prime(2ULL))
printf("2\n");
if (prime(3ULL))
printf("3\n");
for (c = 5; c < 1000; c += 2)
if (prime(c))
printf("%llu\n", c);
return 0;
}
Fixed code.
The trouble with the original code is that it stops checking too soon because divisor is set to the larger, rather than the smaller, of the two numbers to be checked.
static int prime(unsigned long long n)
{
unsigned long long val = 1;
unsigned long long divisor = 5;
if (n == 2 || n == 3)
return 1;
if (n < 2 || n%2 == 0 || n%3 == 0)
return 0;
for ( ; divisor<=n/divisor; val++, divisor=6*val-1)
{
if (n%divisor == 0 || n%(divisor+2) == 0)
return 0;
}
return 1;
}
Note that the revision is simpler to understand because it doesn't need to explain the shorthand negated conditions in tail comments. Note also the +2 instead of -2 in the body of the loop.
He's checking for the basis 6k+1/6k-1 as all primes can be expressed in that form (and all integers can be expressed in the form of 6k+n where -1 <= n <= 4). So yes it is a form of sieving.. but not in the strict sense.
For more:
http://en.wikipedia.org/wiki/Primality_test
In case the 6k+-1 portion is confusing, note that you can perform some factorization of most forms of 6k+n and some are obviously composite and some need to be tested.
Consider numbers:
6k + 0 -> composite
6k + 1 -> not obviously composite
6k + 2 -> 2(3k+1) --> composite
6k + 3 -> 3(2k+1) --> composite
6k + 4 -> 2(3k+2) --> composite
6k + 5 -> not obviously composite
I've not seen this little trick before, so it's neat, but of limited utility since a sieve of Eratosthenese is more efficient for finding many small prime numbers, and larger prime numbers benefit from faster, more intelligent, tests.
#include<stdio.h>
int main()
{
int i,j;
printf("enter the value :");
scanf("%d",&i);
for (j=2;j<i;j++)
{
if (i%2==0 || i%j==0)
{
printf("%d is not a prime number",i);
return 0;
}
else
{
if (j==i-1)
{
printf("%d is a prime number",i);
}
else
{
continue;
}
}
}
}
#include<stdio.h>
int main()
{
int n, i = 3, count, c;
printf("Enter the number of prime numbers required\n");
scanf("%d",&n);
if ( n >= 1 )
{
printf("First %d prime numbers are :\n",n);
printf("2\n");
}
for ( count = 2 ; count <= n ; )
{
for ( c = 2 ; c <= i - 1 ; c++ )
{
if ( i%c == 0 )
break;
}
if ( c == i )
{
printf("%d\n",i);
count++;
}
i++;
}
return 0;
}