I need to check the divisibility of a number in c. How can I use the modulus operatpr in C to check if a number is divisible by another number? I tried doing this:
if (file_int % 3) {
printf("Hoppity \n");
}
It didn't work, although file_int is equal to 9.
What did I do wrong?
Thanks
It didn't work because the operation will return 0 which will be treated as false.
You actually need:
if(!(file_int % 3)) {
printf("Hoppity \n");
}
if (file_int % 3) is the same as if (file_int % 3 != 0), which is the opposite of what you want.
if (file_int % 3 == 0) {
printf("Hoppity \n");
}
// or
if (!(file_int % 3)) {
printf("Hoppity \n");
}
If the result of the modulus is 0, it is evenly divisible. It would appear you are looking for it to be not divisible by 3 to continue the loop, though your code snippet is not sufficient to confidently assume your intent.
because if it is divisible by 3 file_int % 3 will be equal to 0, and the if block won't execute.
Try
if(file_int % 3 == 0) {
// do stuff
}
The mod operator returns the remainder resulting from the division... since 9 is divisible by three with no remainder, the return would be zero.
However, conditional statements evaluates to true if non-zero, false if zero. You need to change it to (file_int % 3 == 0).
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
Following code has no output when it executes. Can anyone explain the following code?
int main() {
int i, j;
for (i = 0; i < 10; i++) {
if (i % 2)
printf("%d\t", i);
else
break;
}
}
0 % 2 gives false so the loop terminates at the first iteration without calling the printf.
Your code has two issues:
1.
if (i % 2)
The condition of (i % 2) evaluates to false because the calculation - 0 divided by 2 - result in 0 -> 0 / 2 = 0. The remainder is also 0.
2.
else break;
That provides the result if (i % 2) is not true (which is the case with 0 at the first iteration) you immediately will break out of the for loop. Omit the break; statement in general, if you want to proof if all values from 0 to 9 have an remainder when divided by 2 or not.
Note that to pack break; in an separate else statement is nonetheless redundant.
Side note:
j has no use in your code.
I guess what you want is something like that:
#include <stdio.h>
int main (void) {
int i, j;
for ( i = 0; i < 10; i++ ) {
if ( ( j = i % 2 ) )
printf("(%d / 2) has a remainder of %d.\n", i, j);
else
printf("(%d / 2) has no remainder.\n", i);
}
}
Output:
(0 / 2) has no remainder.
(1 / 2) has a remainder of 1.
(2 / 2) has no remainder.
(3 / 2) has a remainder of 1.
(4 / 2) has no remainder.
(5 / 2) has a remainder of 1.
(6 / 2) has no remainder.
(7 / 2) has a remainder of 1.
(8 / 2) has no remainder.
(9 / 2) has a remainder of 1.
Try this code online.
Note that by the division 1 / 2, the result 0.5 is raised to the nearest upper integral value 1 because of the implicit double to int conversion.
i % 2 gives the remainder of the Euclidian division of i by 2. It does NOT mean "i is divisible by 2". If the latter is true, then i % 2 gives 0 which implicitely converts to false. If it is false, then i % 2 gives 1 which implicitely converts to true. Therefore, in the first iteration, the conditional ex^pression evaluates to false so you break out of the loop immediately.
If you want to check the divisibility of i by 2, you must use i % 2 == 0.
I am attempting to solve a hw problem in which I need to write down what the program will output. I am stuck however, on the syntax "if ( !(i%3)). What does that really mean? Does it mean that the program is checking for any i that is divisible by three? aka, is the if statement only runs if i is divisible by three?
int main () {
for (int i=0; i<10; (i<3?i++;i+=2)) {
if (!(i%3)) {
continue;
}
else if (i%7 ==0) {
break;
}
cout << i<< endl;
}
Does it mean that the program is checking for any i that is divisible by three? aka, is the if statement only runs if i is divisible by three?
Correct. The longer version of that check would be
if (i % 3 == 0)
continue;
The most common use case for such branching is probably FizzBuzz.
İt means if i is not(!) divisible by 3 continue.
For example if i is 3,6,9 it won't continue otherwise it will continue.
if (x) where x is int implicitly compared with zero. I.e. if (x) equals to if (x != 0). ! is negation. So if (!x) equals to if (x == 0). And the last step is if (!(i%3)) equals to if ((i%3) == 0) what is the same with check, that i deivisible by 3
The if() statement is false only if the result inside the parentheses is 0 (false). Take a look at your program:
i%3 may return 0 (false), 1 (true), or 2 (true)
The negation operator ! changes the result of the operation (i%3). So, if the i is divisible with 3 the statement will return 0 (false). Being negate, ! it will result in True. Otherwise the result of (i%3) will be true and with the operator ! the result of the hole statement will be false. Basically this code is checking if the value of i is divisible with 3.
Other options will be:
if (0==i%3)
{
/*code*/
}
Your code can be simplified as below
int main() {
for (int i=0; i<10;)
{
if (i % 3 == 0) {
continue;
}
else if (i % 7 == 0) {
break;
}
cout << i << endl;
i = i<3 ? i+1 : i+2;
}
}
When you write a integer variable like i as a condition, what happens is that if i==0 then the result of the condition is false, otherwise it would be true.
Let's check it out in your program, if(!(x%3)), let's name condition= !(x%3), when this condition is true? when x%3 == 0, note that the negation operator ! is behind x%3, so in this case the condition would be equal to true, more formally the condition is equal to :
if(x%3==0)
these kinds of conditions are common, check this example out :
int t = 10;
while(t--){
cout<<t<<endl;
}
The above condition i.e if(!(i%3)) will true when " i is not disvisable by 3"
Hope this helps.
In java and other languages there is a special type to represent booleans and evaluate expressions; in c and its variants there is no such thing, instead an expression is considered "true" if -taken as a integer number- is equal to 0; false for every other value. (Fun fact: this is why you usually end the code by return 0)
So if(x%3) in c is equivalent to if(x%3==0) in other languages. That said, if(x%3) execute the if body when the remainder of x/3 is 0, that is when x is a multiple of 3.
In your code you have the ! before, that -as you may know- "inverts" the expression. That means that if(!(x%3)) can be read as "If the remainder of the integer division of x by 3 is not 0", or alternatively: "If x is not a multiple of 3".
So, basically, you saw it right.
Hope I helped!
Prompt: A lucky number is the number has the digit 7 and count of #7 in the number must be odd. Write a recursive function to check whether a number is lucky. (For example, lucky#: 777, 117, 7. not a lucky#: 77, 1277).
I am a beginner. I wrote the code below, but I don't understand how "if(num == 7) return 7" work although it should return a boolean. :(
Here is my code: (it checks if there is any digit 7 and sum off all digit 7 is odd)
bool lucky(int num)
{
if (num < 10)
if (num == 7) return 7; << HOW???? Please!
else return 0;
else if (num % 10 == 7)
return (7 + lucky(num / 10)) % 2 != 0;
else
return lucky(num / 10);
}
In C++ any non-zero value can be considered "true", while zero is "false". Integers are implicitly convertible to bool using this scheme.
Here is a code doing recursion which crashes for larger values:
int rec(int m,int n)
{
if(m==0)
return n+1;
if(m>0 && n==0)
return rec(m-1,1);
if(m>0 && n>0)
return rec(m-1,rec(m,n-1));
}
If I call the function rec(m,n):
with m=1 and n=2, the result I get is 4
with m=2 and n=2, it is 7,
with m=3 and n=2, it is 29
But it crashes for m=4 and m=2. Is there an alternate way to calculate it?
Ackermann's function can be stated non-recursively as
Ack( m, n ) = (2 opm (n + 3)) - 3
where opm is the m'th arithmetic operation in the order addition, multiplication, exponentiation, tower function, ...
In other words it explodes in value pretty darn instantaneously, with no way to represent those numbers as C++ integers.
For an explanation see my homepage from the 1990's :),
(http://web.archive.org/web/20120315031240/http://members.fortunecity.com/alf_steinbach/content/programming/narrow_topics/ackermann/ackermann.html)
rec(4,2)
-> rec(3, rec(4, 1))
->rec(3, rec(4, 0)
->rec(3, 1)
->rec(2, rec(3, 0))
->rec(2, 1)
->rec(1, rec(2, 0)) -->rec(1, 2) //return 4
->rec(1, 0) //return 2 -->rec(0, rec(1, 1)) //return 4
->rec(0, 1) //return 2 -->rec(0, rec(1, 0)) //return 3
-->return 2
this boils down to:
rec(4,2)
-> rec(3, rec(4, 1))
->rec(3, rec(4, 0)
->rec(3, 1)
->rec(2, rec(3, 0))
->rec(2, 1)
->rec(1, 4)
This can be solved further but the space is insufficient and will take a lot of time.
I am predicting that your application either crashes due to stackoverflow or due to reaching the limit of allowable recursions.
But I cannot say for sure...
#Cheers and hth. - Alf explains it mathematically in much more subtle manner ;)
Assume the availability of a function is_prime. Assume a variable n has been associated with a positive integer. Write the statements needed to compute the sum of the first n prime numbers. The sum should be associated with the variable total.
Note: is_prime takes an integer as a parameter and returns True if and only if that integer is prime.
Well, I wrote is_prime function like this:
def is_prime(n):
n = abs(n)
i = 2
while i < n:
if n % i == 0:
return False
i += 1
return True
but it works except for n==0. How can I fix it to make it work for every integer?
I'm trying to find out answers for both how to write function to get the sum of first n prime numbers and how to modify my is_prime function, which should work for all possible input, not only positive numbers.
Your assignment is as follows.
Assume the availability of a function is_prime. Assume a variable n has been associated with a positive integer. Write the statements needed to compute the sum of the first n prime numbers. The sum should be associated with the variable total.
As NVRAM rightly points out in the comments (and nobody else appears to have picked up on), the question states "assume the availability of a function is_prime".
You don't have to write that function. What you do have to do is "write the statements needed to compute the sum of the first n prime numbers".
The pseudocode for that would be something like:
primes_left = n
curr_num = 2
curr_sum = 0
while primes_left > 0:
if is_prime(curr_num):
curr_sum = curr_sum + curr_num
primes_left = primes_left - 1
curr_num = curr_num + 1
print "Sum of first " + n + " primes is " + curr_sum
I think you'll find that, if you just implement that pseudocode in your language of choice, that'll be all you have to do.
If you are looking for an implementation of is_prime to test your assignment with, it doesn't really matter how efficient it is, since you'll only be testing a few small values anyway. You also don't have to worry about numbers less than two, given the constraints of the code that will be using it. Something like this is perfectly acceptable:
def is_prime(num):
if num < 2:
return false
if num == 2:
return true
divisor = 2
while divisor * divisor <= num:
if num % divisor == 0:
return false
divisor = divisor + 1
return true
In your problem statement it says that n is a positive integer. So assert(n>0) and ensure that your program outer-loop will never is_prime() with a negative value nor zero.
Your algorithm - trial division of every successive odd number (the 'odd' would be a major speed-up for you) - works, but is going to be very slow. Look at the prime sieve for inspiration.
Well, what happens when n is 0 or 1?
You have
i = 2
while i < n: #is 2 less than 0 (or 1?)
...
return True
If you want n of 0 or 1 to return False, then doesn't this suggest that you need to modify your conditional (or function itself) to account for these cases?
Why not just hardcode an answer for i = 0 or 1?
n = abs(n)
i = 2
if(n == 0 || n == 1)
return true //Or whatever you feel 0 or 1 should return.
while i < n:
if n % i == 0:
return False
i += 1
return True
And you could further improve the speed of your algorithm by omitting some numbers. This script only checks up to the square root of n as no composite number has factors greater than its square root if a number has one or more factors, one will be encountered before the square root of that number. When testing large numbers, this makes a pretty big difference.
n = abs(n)
i = 2
if(n == 0 || n == 1)
return true //Or whatever you feel 0 or 1 should return.
while i <= sqrt(n):
if n % i == 0:
return False
i += 1
return True
try this:
if(n==0)
return true
else
n = abs(n)
i = 2
while i < n:
if n % i == 0:
return False
i += 1
return True