Home > Blockchain >  Can Some one please explain how does this code work?
Can Some one please explain how does this code work?

Time:10-01

VS CODE IMAGE - I want to understand the if statement and for loop part of this code , can somebody please elaborate this.

CodePudding user response:

The for loop takes the number passed and checks if it is divisible (by checking if the remainder of the division is 0) by each number starting from 2. If it is divisible by a number, the returned value isPrime is set to false, otherwise isPrime will remain true and it will be returned. The for loop stops at the square root of the number passed.

I.e., if the number 17 is passed as argument, it will be divided by 2, by 3 and by 4. It will return true because none of the values assumed by i gave a remainder of 0 in the division. If the number 26 is passed, it will be divided by each integer up to 5, and the function will return false because the remainder of the division by 2 is 0.

CodePudding user response:

dart will execute the code that is inside void main() {}. Inside main() there are 2 functions.

  1. isNumberDivisible: This function takes 2 integers number and divisor and returns a bool value. The logic of the function is that, if the number is dividable with the divisor then it will return true. if not, it will return false.

  2. isPrime: This function takes an integer number and returns a bool value. The logic of the function is, if the number is a prime it returns true, if not it will return false. The way it determines whether it is a prime is by checking if the the testing value: number is not dividable with every value until the root of number (using the function isNumberDivisible). (for example, if you want to test if 100 is a prime, you only have to check if it is not dividable with 2 to 10.)

Lastly, you are calling the isPrime function and testing the value 6 whether it is a prime. which should return false.

  • Related