diff --git a/.github/workflows/check_lesson_06_pr.yaml b/.github/workflows/check_lesson_06_pr.yaml new file mode 100644 index 000000000..d270f9d28 --- /dev/null +++ b/.github/workflows/check_lesson_06_pr.yaml @@ -0,0 +1,32 @@ +name: Check Lesson 06 Pull Request + +on: + pull_request: + branches: [ "main" ] + paths: + - "lesson_06/expression/**" + +jobs: + build: + + runs-on: ubuntu-latest + permissions: + contents: read + + steps: + - uses: actions/checkout@v4 + + - name: Use Node.js + uses: actions/setup-node@v4 + with: + node-version: '20.x' + + - name: Build Shared Lib with Node.js + working-directory: ./lib/typescript/codedifferently-instructional + run: npm ci + + - name: Build Lesson 06 with Node.js + working-directory: ./lesson_06/expression + run: | + npm ci + npm run check \ No newline at end of file diff --git a/.github/workflows/check_push.yml b/.github/workflows/check_push.yml index 65ecc3683..809ba0917 100644 --- a/.github/workflows/check_push.yml +++ b/.github/workflows/check_push.yml @@ -56,4 +56,10 @@ jobs: npm run compile npm run lint + - name: Build Lesson 06 with Node.js + working-directory: ./lesson_06/expression + run: | + npm ci + npm run compile + diff --git a/lesson_04/amiyahjones/README.md b/lesson_04/amiyahjones/README.md new file mode 100644 index 000000000..21a1db9e8 --- /dev/null +++ b/lesson_04/amiyahjones/README.md @@ -0,0 +1,50 @@ +## Javascript +``` javascript + +function isPrime(num) { + if (num < 2) { + return false; // Numbers less than 2 are not prime + } + + for (let i = 2; i < num; i++) { + if (num % i === 0) { + return false; + } + } + + return true; +} + +console.log(isPrime(5)); //true +console.log(isPrime(1)); //false + +``` +## Ruby +###### Tutorial used : https://www.youtube.com/watch?v=33pLqGvk-PM +``` ruby +def prime?(n) +# '2..n-1' checks all the numbers from 2 up to less than 'n'. +# 'none' -> sees if none of these numbers can divide 'n' evenly. + (2..n-1).none? {|divisor| n % divisor == 0} +# If none of these numbers divide 'n' without a remainder, +# then 'n' is a prime number. Otherwise, it's not. +end + +p prime? 5 # prints 'true' +p prime? 6 # prints 'false' +p prime? 7 # also 'true' +``` + + +## Explanation + +My JavaScript implementation uses a function named ```isPrime``` that checks if a number is prime by first returning `false` if the number is less than 2, since prime numbers are greater than 1. Then, it tests every number from 2 up to one less than the given number to see if any of them can divide it without leaving a remainder. If it finds one that can divide it evenly, it returns `false` ; if not, it returns `true`, meaning the number is prime. + +The ruby implementation has a function named ```prime?``` that also looks at all the numbers from 2 up to one less than the number given. Same rules apply: If none of those numbers can divide it evenly, then it prints ```true```. For example, it tells us if 5 and 7 are prime (they are!) and if 6 is prime (it’s not!). + +### Differences +1. Instead of ```function``` used to define what your function is in javascript, Ruby use ```def``` +2. Ruby is much more simple - where tthe ```if``` and ```else``` statement is simply in one line +3. Ruby simply 'prints' the result of its functions rather than ```console.log();``` + + diff --git a/lesson_04/chigazograham/README.md b/lesson_04/chigazograham/README.md new file mode 100644 index 000000000..99432cc8c --- /dev/null +++ b/lesson_04/chigazograham/README.md @@ -0,0 +1,70 @@ +## Python implementation + +```python +def is_prime(num): +# uses the function is_prime and takes the argument num + if num > 1: +# gets rid of numbers 1 and lower as the first prime number is 2 + for i in range(2, (num // 2) + 1): +# tells the computer to look at all numbers between 2 and half of the value of num rounded up to the next nearest value using floor division + if(num % i) == 0: +# then divides the num value, using modulo division, by every number in the range of two to +infinity + return False +# if the remainder in equivalent to 0 then the number is not prime and returns False + else: + return True +# if the remaineder is not equivalent to 0 then the terminal will return True + else: + return False +# for all other real numbers that arent prime the terminal will reurn False + +print(is_prime(19)) #Output: True +print(is_prime(9)) #Output: False +``` + +## Ruby implementation + +```ruby +def isPrime(n) +#uses the function isPrime and takes the argument n + return false if n <= 1 +#the computer will reurn false for all numbers less than or equal to zero + return true if n == 2 || n == 3 +#tells the computer to return true if the n is equivalent to 2 or 3 + + return false if n % 2 == 0 || n % 3 == 0 +#returns false if n is divisible by two or 3 + + i = 5 +#defines i starting value as 5 + while i * i <= n +#while n is greater than or equal to 25 + return false if n % i == 0 || n % (i + 2) == 0 +#return false if n is divisible by 5 or 7 + i += 6 +#adds 6 to the value of i if n is not divisible by 5 or 7 and runs the loop again + end + true +#returns true for all numbers that arent divisible by 2, 3, 5, or 7 +end +puts isPrime(17) #Output: true +puts isPrime(24) #Output: false +``` + +## Explanation + +The Python implementation uses a function named `is_prime` that takes a single argument `num`. It returns `False` if the number is 1 or less or divisible by any number from two to half the value of `num` (i.e., when the remainder of the division of the number by 2 is zero), otherwise, it returns `True` and returns any possible other values as false. + +The Ruby implementation uses a function named `isPrime` that also takes a single argument `n`. It returns `true` if the number is equivalent to 2 or 3 and if the number is not divisible by 2 or 3 and 5 or 7 if the number is over 25 and `false` if otherwise. + +### Differences + +1. **Syntax**: + - Python uses `True` and `False` for boolean values, while Ruby uses `true` and `false`. + - The formatting for `if` statements are also different between the two. In Python, `if` statements have the initial statement and then on the next line the command to run if the variable falls under the `if` statement. In Ruby the formatting is completely different, the command comes first and after that the `if` statement comes in on the same line + - In Python, a colon(`:`) is used to close function statements, whereas in Ruby there is nothing closing the function statements. + - Ruby can return true or false without a return statement. In contrast Python requires a return statement or will return with `None`. + - Ruby has to be closed in `end` after loops or an error will appear and the code won't run. Python, on the other hand doesn't need anything and will return with `None` instead of an error if not given further instructions. + - The syntax for calling functions and printing to the console/output is different. Python uses `print()`, while Ruby uses `puts()`. + + \ No newline at end of file diff --git a/lesson_04/davidsmith/README.md b/lesson_04/davidsmith/README.md new file mode 100644 index 000000000..779c69aca --- /dev/null +++ b/lesson_04/davidsmith/README.md @@ -0,0 +1,30 @@ +## Java Method +```java +public static boolean isPrime(int n) { + if (n <= 1) return false; + for (int i = 2; i <= Math.sqrt(n); i++) { + if (n % i == 0) { + return false; + } + } + return true; +} +``` +## Python Method +```python +def is_prime(n): + if n <= 1: + return False + for i in range(2, int(n**0.5) + 1): + if n % i == 0: + return False + return True +``` + +## Understanding The Code + +Java and Python are similar in some ways. They have the same function structures. The `isPrime` method is in Java. The `is_prime` function is in Python. Both check if \( n \) is less than or equal to 1. They return false if this is true. Then, they use a for-loop. The for-loop finds factors from 2 to the square root of \( n \). Java needs explicit type declarations. Python does not need explicit type declarations. However, the logical flow is similar. This shows their focus on clarity. It makes both languages friendly for users. It also makes them easy for developers with different skills. + +## Differences + +Java and Python have big differences in syntax. They also have differences in structure. The `isPrime` method shows this. The `is_prime` function also shows this. Java is statically typed. It needs explicit type declarations like `int n`. Python is dynamically typed. It allows defining variables without a type. Java uses the `Math.sqrt` method. This method is for calculating square roots. Python uses the expression `n**0.5` for this. The for-loop syntax is different too. Java has a traditional for-loop with an initializer. Python uses the `range` function for loops. These differences show the different design philosophies. They also show different approaches to readability for each language. \ No newline at end of file diff --git a/lesson_04/jimoye244/README.md b/lesson_04/jimoye244/README.md new file mode 100644 index 000000000..707c36f63 --- /dev/null +++ b/lesson_04/jimoye244/README.md @@ -0,0 +1,55 @@ +## Java implementation + +```Java +static boolean isPrimeNumber(int number){ + int zeroRemainderCount=0; + for(int i=1; i <= number; i++){ + if(number % i == 0) zeroRemainderCount++; + } + + return zeroRemainderCount == 2 ? true : false; +} + +# Example usage: +System.out.println(isPrimeNumber(7)) # Output: true +System.out.println(isPrimeNumber(12)) # Output: false +``` + +## JavaScript implementation + +```javascript +function isPrimeNumber(number){ + let zeroRemainderCount = 0; + for(i=0; i<=number; i++){ + if(number % i === 0) zeroRemainderCount++; + } + return (zeroRemainderCount === 2) ? true : false; +} + +// Example usage: +console.log(isPrimeNumber(11)); // Output: true +console.log(isPrimeNumber(81)); // Output: false +``` + +## Explanation + +The Java implementation uses a function named `isPrimeNumber` that takes a single argument `number`. It returns `true` if the number is prime (e.g, when the zero remainder count of the division of the number by numbers between 1 and itself is two), otherwise, it returns `false`. + +The JavaScript implementation uses a function named `isPrimeNumber` that also takes a single argument `number`. It returns `true` if the number is prime (using the same logic as the Java function) and `false` otherwise. + +### Improvement in the Function Implementation: +For large numbers, it will be reasonable to exit the loop once the zero remainder count reaches a value of 3. + +### Differences + +1. **Syntax**: + - In Java, functions are defined by specifying the function name which is preceeded by the return type i.e `boolean isPrimeNumber`, whereas in JavaScript, the `function` keyword preeceds the function name i.e `boolean isPrimeNumber`. + + The loop variable `i` was initialize with a value 0 that is type-annotated `int` in Java implementation. However, in JavaScript implementation, the variable `i` was not type-annotated. + +2. **Equality Check**: + - Java uses `double equal sign (==)` to test equality whereas JavaScript uses `tripple equal sign (===)` to test equality. + +3. **Function Calls**: + - The syntax for calling functions and printing to the console/output is slightly different. Java uses `System.out.println() or System.out.print()`, while JavaScript uses `console.log()`. + diff --git a/lesson_04/josephcaballero/README.md b/lesson_04/josephcaballero/README.md new file mode 100644 index 000000000..9aa851609 --- /dev/null +++ b/lesson_04/josephcaballero/README.md @@ -0,0 +1,76 @@ +## Javascript Implementation +```javascript +const prime = (num) => { + if(num <2){console.log(num + " is not a prime number")} + else{ + for(let i = 2; i<=10; i++){ + if(num%i !== 0){ + if(i ===10){ + console.log(num + " is a prime number") + break; + } + else{ + continue; + } + } + else if(num%i===0 && num !==i){ + console.log(num + " is not a prime number") + break; + } + else if(num===2){ + console.log(num + " is a prime number") + break; + } + } + } +} +prime(2) // output: 2 is a prime number +prime(11) // output: 11 is a prime number +prime(12) // output: 12 is not a prime number +``` +## Python Implementation +```python + +def prime(num): + if(num <2): + print(num , " is not a prime number") + else: + for i in range(2,11): + if num % i != 0: + if i ==10: + print(num , " is a prime number") + break + + else: + continue + + + elif num%i==0 and num !=i: + print(num , " is not a prime number") + break + + elif num==2: + print(num , " is a prime number") + break + else: + continue + +prime(2) # output: 2 is a prime number +prime(11) # output: 11 is a prime number +prime(113) # output: 113 is a prime number +``` + +## Explanation +My codes both use a function called prime with a parameter of num (num is to be filled with a number). The function is comprised of an if statement first with a condition that checks that the number entered isnt a number less than 2 (due to the fact that any number below 2 is not prime). Next is an else statement for when the number that was given in the parameter is not less than 2. After that is a for loop nested (meaning inside) in the else statement to iterate over a set group of numbers which in my case are 2-10 (because if a number is divided by these numbers and reaches 0 it is not a prime number, in the code it is shown as 2,11 however the digit on the right does not get reached and thus goes up to 10). Then if loops to meet certain conditions, in these if loops I use the percentage sign % which is modulator (mod for short) which checks if there is a remainder after division, be it 10/2 "which is 0" or 13/2 "which is 1" if there is a remainder it is prime and if there is not it is not prime(after all iterations). I used the code to take the number given to me and then checked if every number between 2-10 that was %(modded) by the given number did not meet 0 because if it did that would not be a prime number. To bypass the question of "what if the number you input gets iterated over in the for loop", i set a parameter that skips over that iteration by simply making use of the else loop so that any other iteration would be looked at and not that duplicate numbered one. + +In python I did this using the def prime(): code "prime being the function name" + +In javascript i did the exact same thing however I made a constant function which is just easier to debug. by doing const prime = (condition) => {code} + +### Difference +1. **Syntax**: +- In python the syntax feels much more friendly by looking at it however is is alot scarier when you delve deep into it as you can make loops and function just by using if(condition): or for i in range(): as long as you are matching line indents, not to mention no ; which is alot more responsibility on the programmer +- In javascript it feels much more safer but cluttered, the {} help show where exactly everything is in a more contained way but takes up space, and the ; are nice however they are an extra character, it is a give some take some scenario between these two languages +2. **Different Signs**: +- In Python you use different signs , like the print statement itself, how the statement is structured with a comma, and no parenthesis between most things that javascript would have +- In Javascript the equivalent of print is console.log(), also in the log you put + to combine two values even if they arent the same to yield a log displayed in the console, and there are many more parenthesis like in the conditional statements diff --git a/lesson_04/kimberleehaldane/README.md b/lesson_04/kimberleehaldane/README.md new file mode 100644 index 000000000..aaeb1c7fc --- /dev/null +++ b/lesson_04/kimberleehaldane/README.md @@ -0,0 +1,118 @@ +## Java Implementation + +```java +if (n <= 1) { + System.out.println(n + " is not a prime number."); +} else if (n == 2) { + System.out.println(n + " is a prime number."); +} else if (n % 2 == 0) { + System.out.println(n + " is not a prime number."); +//ChatGPT helped me to complete the code from this point.// +} else { + boolean isPrime= true; + for (int i = 3; i <= Math.sqrt(n); i += 2) { + if (n % i == 0) { + isPrime = false; + break; + } + } + if (isPrim) { + System.out.println(n + " is a prime number."); + } else { + System.out.println(n + " is not a prime number."); + } +} + +# Example Usage: +Input: n = 7 +Output: if (7 <= 1) // Result: No, 7 is not less than or equal to 1 + else if (7 == 2) // Result: No, 7 is not equal to 2 + else if (7 % 2 == 0) // Result: No, 7 mod 2=1, 7 is not even + else + boolean isPrime = true // Initialize a boolean variable to true to check for odd factors + for (int i = 3; i <= Math.sqrt(7; i += 2) // Result: √7 ≈ 2.645, 3<=2.645, Answer: No, so isPrime is true + Print Result: 7 is a prime number. +``` + +## C++ Implementation + +```c++ +// C++ code created and explained with the help of ChatGPT and Google Search +bool isPrime(int number) { + // Handle special cases + if (number <= 1) return false; // 0 and 1 are not prime numbers + if (number <= 3) return true; // 2 and 3 are prime numbers + + // Check for even numbers greater than 2 + if (number % 2 == 0) return false; + + // Check for factors from 3 to the square root of the number + for (int i = 3; i * i <= number; i += 2) { + if (number % == 0) return false; // Found a factor + } + + return true; // No factors found, number is prime +} + +int main() { + int num; + std::cout << "Enter a number: "; + std::cin >> num; + + if (isPrime(num)) { + std::cout << num << " is a prime number." << std::endl; + } else { + std::cout << num << " is not a prime number." << std::endl; + } + + return 0; +} + +# Example Usage: +Input: isPrime(7) +Output: if (7 <= 1) return false // Result: 7 is not less than or equal to 1 + if (7 <= 3) return true // Result: 7 is greater than 3 + if (7 % 2 == 0) return false // Result: 7%2=1 + for (int i = 3; i * i <= 7; i += 2) // Result: i starts at 3, 3 * 3 <= 7, 9 <= 7, false + return true // Result: No factors found +Print Result: Since isPrime(7) returned true: 7 is a prime number. +``` + + +## Explanation + +### Thought Process + +I chose to use the programming languages Java and C++. I chose Java because I have been introduced to it before through Codio and have an introductory level understanding of some concepts. I chose C++ because after understanding what a prime number is and its uses, I found that it is a crucial part of cryptography. The difficulty of factoring large prime numbers makes it ideal for creating secure encryption algorithms. Due to its high performance, control over memory management, and ability to optimize code for speed, especially for complex algorithms and time sensitive situations, C++ has the title of being one of the best programming languages for creating encryption algorithms. (Source: Google search, AI) + +### Implementation + +The Java implementation determines if a number is a prime number by: + +- Understanding what a prime number is (a number that is greater than 1 and is only divisible by 1 and itself), then setting up the logic. + +- Use a boolean variable `isPrime` in an if/else conditional statement. If `isPrime` returns false, n is not a prime number. If `isPrime` returns true, n is a prime number. + +The C++ implementation determines if a number is a prime number by: + +- Using a conditional statement within a function. + +- The `main` function takes user input and uses the `isPrime` function to determine if a number is a prime number. If `isPrime` returns true, n is a prime number. If `isPrime` returns false, n is not a prime number. + +### Similarities + +- Both programming languages used conditional statements with true/false values to determine if a number is a prime number. + +- Similar syntax: `isPrime` + +- Similar code operation: Start with special cases `n<=1, n<=3`, then check for even numbers greater than 2, loop to check factors before coming to the output. + +### Differences + +1. **Syntax**: +- In Java, the true/false value is called `boolean`, whereas in C++ the true/false value is called `bool`. +- C++ uses a `main` function to take user input during the output process, while in Java it is assumed that the `isPrime` starts off as true until proved false. + +2. **Function Calls**: +- The syntax for printing to the console/output is different. Java uses `System.out.println()`, while C++ uses `std::cout << "insert string" << std::endl;`. +`(Source: ChatGPT, Google Search, Codio notes)` diff --git a/lesson_04/ljmcwilliams/README.md b/lesson_04/ljmcwilliams/README.md new file mode 100644 index 000000000..5ca25dc29 --- /dev/null +++ b/lesson_04/ljmcwilliams/README.md @@ -0,0 +1,59 @@ +In this lesson, I explored the differences between Java and JavaScript. Despite their similar names, these languages have distinct features. + +- ## Key Differences +- ### Document Preparation: + + - Java requires preparation before defining variables and functions. +JavaScript has more flexibility with variable definitions. + +- ### User Input: + + - In Java, I used the Scanner class to prompt the user for number input. +This required importing Java's Scanner class. +In JavaScript, there is no built-in Scanner class, so I used Node.js as a workaround. +With Node.js, I utilized process.stdin for input and process.stdout for output (similar to console.log). + +- ### Loop Control: + + - Both languages allow for loops to be exited early, but the methods differ: +In Java, using a break statement within the loop will terminate it. +In JavaScript, I opted for read.close(), which achieves a similar effect. + +- ### Variable Declaration: + + - Java requires explicit declaration of variable types. +JavaScript automatically assigns variable types. +- ## Loop Behavior +Both languages share similarities in loop functionality: + +- **For Loops**: + - Take three expressions. + +- **If Statements**: + - Accept a condition and can be nested. + +- **Java Example** +```java +for (int i = 2; i < userInput; i++) { + if ((userInput / i) == (int) (userInput / i)) { + System.out.println(userInput + " is not a prime number."); + isConditionMet = true; + break; + } + } if (!isConditionMet) { + System.out.println(userInput + " is a prime number."); + } +``` +- **JavaScript Example** +```javascript +for (let i = 2; i < answer; i++) { + if ((answer / i) == parseInt(answer / i)) { + console.log(answer + " is not a prime number."); + isConditionMet = true; + read.close(); + } + } if (!isConditionMet) { + console.log(answer + " is a prime number."); + read.close(); + } +``` \ No newline at end of file diff --git a/lesson_04/ljmcwilliams/findPrimeNum.java b/lesson_04/ljmcwilliams/findPrimeNum.java new file mode 100644 index 000000000..3b588aae5 --- /dev/null +++ b/lesson_04/ljmcwilliams/findPrimeNum.java @@ -0,0 +1,32 @@ +import java.util.Scanner; //This allows us to use the scanner to take in user input +public class findPrimeNum { + public static void main(String[] args) { + Scanner objScanner = new Scanner(System.in); //A scanner named 'objScanner' + boolean isConditionMet = false; + + /*if the condition is met, the print statement within the loop will be printed. + If not, the print statement after the loop will be printed*/ + + System.out.print("Please enter a whole number: "); //User input prompt + double userInput = objScanner.nextDouble(); //This reads an integer value from the user + + /*to determine a number's primality, we can check to see if the division + of that number by 2 to (1 - that number) results in any whole number quotients. + Once we do the division we can compare that number to (int) number to see if the + values are equal.*/ + + /*the program should end if A: the first whole number quotient is found, indicating that + * indicating a number is not prime or if B: no whole number quotients are found within the + * range indicating the number IS prime.*/ + + for (int i = 2; i < userInput; i++) { + if ((userInput / i) == (int) (userInput / i)) { + System.out.println(userInput + " is not a prime number."); + isConditionMet = true; + break; //this helps jump out of the loop once this first whole number quotient instace is found + } + } if (!isConditionMet) { + System.out.println(userInput + " is a prime number."); + } + } +} \ No newline at end of file diff --git a/lesson_04/ljmcwilliams/findPrimeNum.js b/lesson_04/ljmcwilliams/findPrimeNum.js new file mode 100644 index 000000000..3b78c3b49 --- /dev/null +++ b/lesson_04/ljmcwilliams/findPrimeNum.js @@ -0,0 +1,21 @@ +const readline = require('readline'); //"require()" imports the readline module which will process the user input +const read = readline.createInterface({ + input: process.stdin, //this acts as an input scanner + output: process.stdout //this works like a normal console.log combined with a user's input +}); +let isConditionMet = false; + +/* When looking at the Node.js docs, it states '.question()' displays the query (in this case the user prompt). +It waits for an input and uses it as the first argument in a callback function (here I am using a arrow function). */ +read.question("Enter a number: ", (answer) => { + for (let i = 2; i < answer; i++) { + if ((answer / i) == parseInt(answer / i)) { //similar to the "(int)" statement in java, parseInt converts doubles to ints + console.log(answer + " is not a prime number."); + isConditionMet = true; + read.close(); //this works similar to a break statement in java and ends the program + } + } if (!isConditionMet) { + console.log(answer + " is a prime number."); + read.close(); + } +}) \ No newline at end of file diff --git a/lesson_04/shawndunsmore/README.md b/lesson_04/shawndunsmore/README.md new file mode 100644 index 000000000..5f68d3f23 --- /dev/null +++ b/lesson_04/shawndunsmore/README.md @@ -0,0 +1,42 @@ +## Java Method +```java + +if (number <= 1){ + return false; +} + +for (int i = 2; <= Math.sqrt(number); i ++){ + if (number % i == 0){ + return false; + } +} + +return true; + +``` + +## Python Method +```Python +def is_prime(number): + if number <= 1: + return False + + for i in range(2, int(math.sqrt(number)) + 1): + if number % i == 0: + return False + + return True +``` +## Explanation + We start off with both methods making sure the input number is less then or equal to one. Then it redirects down to see if the number comes back as false. Once checked with i to see if the number can be divided by one its checked through with are % operator. Once are loop is complete if it tracks no false numbers then it'll return true. + + +## Differences +* Both functions are called differently (`java: system.out.print` `Python print`) + +* Both languages import math differently (`java: import java.lang.Math`; `Python: import math`) +## Similarities +* Both languages use `math.sqrt` equally to find the square root of the number. (well if you wanna be technical "java" has it start with a capital M but come on man.) + +* In both methods Java and Python still use if statements to make choices in the code. +"Used Ai to give me code prompts of python and java" \ No newline at end of file diff --git a/lesson_04/tommytran/lesson_4.java b/lesson_04/tommytran/lesson_4.java new file mode 100644 index 000000000..64200521a --- /dev/null +++ b/lesson_04/tommytran/lesson_4.java @@ -0,0 +1,35 @@ +public class lesson_4 { + + // Function to check if a number is prime + public static boolean isPrime(int n) { + if (n < 2) { + return false; // Numbers less than 2 are not prime + } + if (n == 2) { + return true; // 2 is the only even prime number + } + if (n % 2 == 0) { + return false; // Numbers divisible by 2 are not prime + } + // Loop that checks every odd number up to the square root of n + for (int i = 3; i <= Math.sqrt(n); i += 2) { + if (n % i == 0) { + return false; // n is divisible by i, so it's not prime + } + } + return true; // n is prime + } + + public static void main(String[] args) { + // Declare integers in main method + int a = 1; + int b = 9; + int c = 17; + + // Return string of whether or not int is a prime number + System.out.println("Is " + a + " a prime number? " + isPrime(a)); + System.out.println("Is " + b + " a prime number? " + isPrime(b)); + System.out.println("Is " + c + " a prime number? " + isPrime(c)); + } +} +// code sourced from chat-gpt after converting my JS file. diff --git a/lesson_04/tommytran/lesson_4.js b/lesson_04/tommytran/lesson_4.js new file mode 100644 index 000000000..3848224b9 --- /dev/null +++ b/lesson_04/tommytran/lesson_4.js @@ -0,0 +1,29 @@ + + //declare integers in function: sample numbers + let a = 1; + let b = 9; + let c = 17; +{ +function Prime(n) { + if (n < 2) { + return false; // Numbers less than 2 are not prime + } + if (n === 2) { + return true; // 2 is the only even prime number + } + if (n % 2 === 0) { + return false; // numbers divisible by 2 are not prime + } + // loop that checks every odd number up until square root of n + for (let i = 3; i <= Math.sqrt(n);i +=2) { + if (n % i === 0) { + return false; // n is divisible by i, so it's not prime + } + } + return true; // n is prime +} +//return string of whether or not int is a prime number +console.log(`Is ${a} a prime number? ${Prime(a)}`); +console.log(`Is ${b} a prime number? ${Prime(b)}`); +console.log(`Is ${c} a prime number? ${Prime(c)}`); +} \ No newline at end of file diff --git a/lesson_04/tommytran/readme.md b/lesson_04/tommytran/readme.md new file mode 100644 index 000000000..ff07886c3 --- /dev/null +++ b/lesson_04/tommytran/readme.md @@ -0,0 +1,20 @@ +## Explanation + + +First I declared 3 variables to use to test my function a,b, and c. I then assigned 3 integers to these variables to test this function. I created a function by the name of prime that contained an if else statement and a for loop. I then created several rules for the the if statement. The first rule determined whether the number was less than 2 then it was considered not a prime number. The second rule was that the number 2 would return true as it is the only even prime number. the third rule was that any number that was divided by 2 would not leave a remainder a 0. If none of those conditions were satisfied then a for loop would activate starting from the number 3. The loop would check all numbers starting at number #3 and must be less than or equal to the square root of (n). The loop would then increase integer by 2 to check every odd number between 3 and the square root. If any number that was determined (n) to be divisible by (i) then it was false and not a prime number. If there was no odd divisble numbers then the statement would return true. Afterwards I would test the function by inputting a console.log command in the terminal to print a string that determined whether or not the number in each variable was a prime number or not. + + +### Similiarities and Differences + + +1. **Syntax**: + - to print messages in the console in javascript you would do console.log + - to print messages in the console in Java you would use the System.out.println command + - although they are different they ultimately perform the same action and the function's are built in a very similar order/pattern. + +2. ** Variables + - In javascript you can declare a variablle using let and achieve a more broader scope of defined objects whereas in Java you have to be more specific with the data type as an int,double,string,etc. + +3. ** Testing + - to run the java you would name the file with a .java at the end and type "java [filename.java]" to run the program + - to run the javascrip you would name the file with a .js at the end and type node [filename.js] to run the program \ No newline at end of file diff --git a/lesson_04/yafiahabdullah/README.md b/lesson_04/yafiahabdullah/README.md new file mode 100644 index 000000000..1efb38880 --- /dev/null +++ b/lesson_04/yafiahabdullah/README.md @@ -0,0 +1,56 @@ +## Javascript isPrimeNumber + +```javascript +function isPrimeNumber(number){ + let result= "not prime"; + if(number <= 1){ + return result; + } + for(let i = 2; i < number; i++ ){ + if(number % i === 0){ + return result; + } + } + return "prime number"; +} +# Example usage: +console.log(isPrimeNumber(4)) # Output: false +console.log(isPrimeNumber(7)) # Output: true +``` + +## Explanation + +The JavaScript function isPrimeNumber checks if a given number is prime. It initializes a result variable with "not prime" and first checks if the number is less than or equal to 1, returning this result if true. Then, it loops from 2 up to the number, checking for divisibility. If the number can be evenly divided by any value in this range, it returns "not prime". If no divisors are found, the function concludes that the number is prime and returns "prime number" + + +## Java isPrimeNumber implementation + +```java +public class PrimeChecker { + public static String isPrimeNumber(int number) { + if (number <= 1) { + return "not prime number"; + } + for (int i = 2; i < number ; i++) { + if (number % i == 0) { + return "not prime number"; + } + } + return "prime number"; + } +} +# Example usage: +System.out.println(isPrimeNumber(4)) # Output: false +System.out.println(isPrimeNumber(7)) # Output: true +``` + +## Explanation + + The Java implementation uses a function named `isPrimeNumber` This function effectively determines if a number is prime by checking its divisibility with all integers from 2 up to that number, providing clear output based on the result. + +### Differences + +1. + Overall, while both languages share some similar structural elements (like curly braces for blocks), Java has stricter syntax rules regarding types and class structure, whereas JavaScript is more flexible with its dynamic typing and function definitions. + +